Spring Session 实现单点登录
此种方式相对于上节(https://blog.csdn.net/sinat_25295611/article/details/80406172)所说使用原生Jedis+Jackson+Cookie+Filter的方式实现起来更加简便,同时对业务代码的侵入性也十分之小,其原理与原生方式类似,并通过对HttpServletRequest和HttpServletResponse的包装来实现cookie的读写,序列化采用JDK原生的方式,故用户对象(User)需要实现Serializable接口,
<dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> <version>1.3.1.RELEASE</version> </dependency> <!-- spring session 的过滤器--> <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>*.do</url-pattern> </filter-mapping> <bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"> <!-- session 过期时间默认为30分钟--> <property name="maxInactiveIntervalInSeconds" value="1800"/> </bean> <!--TODO 自定义写入的Cookie设置 --> <!--<bean id="defaultCookieSerializer" class="org.springframework.session.web.http.DefaultCookieSerializer"> <property name="cookieName" value="SESSION_NAME"/> <property name="cookiePath" value="/"/> <property name="domainName" value=".kaymmall.com"/> <property name="useHttpOnlyCookie" value="true"/> <property name="cookieMaxAge" value="3600*24*365"/> </bean>--> <!-- 连接池配置,这里使用Jedis的连接池--> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="20"/> </bean> <!-- jedisConnectionFactory--> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="127.0.0.1"/> <property name="port" value="6379"/> <property name="poolConfig" ref="jedisPoolConfig"/> </bean> 通过Redis+Spring Session实现的单点登录系统对业务代码侵入性非常小,在单服务器时使用session存取用户信息,在集群模式时代码无需改变,只要引入Spring Session相关配置即可。