Programming/Spring Framework

[Spring] redis 를 통한 session 공유 및 하위 도메인간 세션 공유

통통만두 2022. 7. 15. 10:17
반응형
반응형

spring에서 세션을 공유하는 방법은 여러 가지가 있습니다.

Tomcat, Apache 등등 있지만, 저의 경우에는 3대의 apache + tomcat로 구성된 서비스를 redis를 통해서 세션을 공유하도록 했습니다. 한 동안 잘 사용하고 있다가 다른 서비스를 띄워서 세션을 같이 공유해야하는 상황이 생겼습니다.

기존 사용하던 도메인이 admin.marsland.co.kr 이었다고 하면 신규로 생긴 서비스는 docs.marsland.co.kr 입니다. 흔히 인터넷에 나와 있는 redis를 통한 세션 공유는 도메인이 틀려지면 세션이 공유는 되지 않습니다.

admin.marsland.co.kr에서 로그인을 했을 경우에 docs.marsland.co.kr도메인으로 접근시에도 세션을 공유하여 admin.marsland.co.kr -> docs.marsland.co.kr 호출시 정상적인 접근을 가능하게 합니다.

 

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-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
>

	<context:annotation-config />

	<bean id="defaultCookieSerializer" class="org.springframework.session.web.http.DefaultCookieSerializer">
		<!--
		<property name="domainName" value=".marsland.co.kr"/>
		<property name="cookieName" value="JSESSIONID"/>
		<property name="cookieName" value="MARSLAND_COOKIE_IS_DELICIOUS"/>
		<property name="cookiePath" value="/"/>
		<property name="domainNamePattern" value="^.+?\\.(\\w+\\.[a-z]+)$"/>
		-->
		<property name="domainName" value=".marsland.co.kr"/>
		<property name="cookieName" value="MARSLAND_COOKIE_IS_DELICIOUS"/>
		<property name="cookiePath" value="/"/>
	</bean>

	<bean
		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
		p:usePool="true"
		p:hostName="#{ constConfig['REDIS_SESSION_HOST_NAME'] }"
		p:port="#{ constConfig['REDIS_SESSION_PORT'] }"
		p:database="#{ constConfig['REDIS_SESSION_DATABASE'] }"
		p:password="#{ constConfig['REDIS_SESSION_PASSWORD'] }" />

	<bean id="redisHttpSessionConfiguration"
		  class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
		<property name="maxInactiveIntervalInSeconds" value="1800" />
		<property name="cookieSerializer" ref="defaultCookieSerializer"/>
	</bean>

</beans>

 

저의 경우에는 위의 설정으로 서로 하위 도메인간 세션을 공유했습니다. 로컬에서 테스트를 해보실 때는 hosts 파일을 수정하여서 진행했습니다. 크롬이나 웨일같은 브라우저로 각각 접속시 위에 설정한 cookieName에 생기는지, 그리고 하위 도메인간 해당 쿠키의 값이 동일한지 확인하시면 됩니다.

반응형