Programming/Java

SpringFramework 에서 Redis 를 활용한 Session Storage 분리

armyost 2023. 9. 6. 05:36
728x90

- SpringSession & Redis관련 Bean 생성
SpringSession 라이브러리는 Clustered Session 제공을 위해 Servlet에 비종속적인 Session LifeCycle 관리 라이브러리
※ 스크립트 위치 : /src/main/resources/egovframework/spring/context-*.xml

<!-- redis -->
          <context:annotation-config/>
          <bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"
                   p:maxInactiveIntervalInSeconds="1800" /> <!-- 초단위 세션 유효시간 설정 -->
          <bean id="redisConnectionFactory"
                   class="org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory"
                   p:host-name="redis01.armyost.com" p:port="6379" />
<!-- redis -->

 

- RedisTemplate Bean 생성 ( Template의 경우 커스텀한 설정이 필요할 수 있어 JAVA Config로 정의함)

@Configuration
public class SessionConfig {
          private LettuceConnectionFactory redisConnectionFactory;
 
          @Autowired
          public SessionConfig(LettuceConnectionFactory redisConnectionFactory) {
                   this.redisConnectionFactory = redisConnectionFactory;
          }
 
          @Bean
          public RedisTemplate<String, Object> redisTemplate() {
                   RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
                   redisTemplate.setConnectionFactory(redisConnectionFactory);
                   redisTemplate.getConnectionFactory().getConnection().flushAll();
                   return redisTemplate;
          }
}

 

- Filter 적용

SpringSessionDispatcher Servlet에 종속적인 Interceptor기능을 사용하지 않고 Servlet외부에서 Client Request를 처리할 수 있는 Filter 사용
※ 스크립트 위치 : /src/main/webapp/WEB-INF/web.xml

<!-- redis -->
          <filter>
                   <filter-name>springSessionRepositoryFilter</filter-name>
                   <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
          </filter>
          <filter-mapping>
                   <filter-name>springSessionRepositoryFilter</filter-name>
                   <url-pattern>/*</url-pattern>
                   <dispatcher>REQUEST</dispatcher>
                   <dispatcher>ERROR</dispatcher>
          </filter-mapping>
<!-- redis -->