Spring Session
简介
Spring Session 提供了管理用户session的API 和实现,直接集群环境Sesison管理,单浏览器多个Session,RESTful APIs Session,集群Session 管理集成并不依赖应用程序容器;支持Session存储Redis、GemFire、JDBC、Mongo。
请参考Spring Session docs
使用Redis存储Session
Redis 使用广泛,性能优越,适合集群环境。
使用Spring Boot集成将更加方便:
1. 加入spring-session 依赖
2. 加入spring-data-redis依赖
3. @EnableRedisHttpSession
以下为不使用Spring Boot集成Spring Session :
基于Java 代码配置集成Spring Session
- 加入依赖
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>1.2.0.RELEASE</version>
<type>pom</type>
</dependency>
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
- 在配置类上加入@EnableRedisHttpSession,并配置JedisConnectionFactory Bean
@Configuration
@EnableRedisHttpSession
public class SessionConfig {
@Bean
public JedisConnectionFactory connectionFactory() {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
jedisConnectionFactory.setHostName("172.16.31.84"); // 默认localhost
jedisConnectionFactory.setPort(6379); // 默认6379
jedisConnectionFactory.setDatabase(0); // 默认0
jedisConnectionFactory.afterPropertiesSet();
return jedisConnectionFactory;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 继承AbstractHttpSessionApplicationInitializer,无参构造调用父类方法,传入配置类
public class SessionInitializer extends AbstractHttpSessionApplicationInitializer{
public SessionInitializer() {
super(SessionConfig .class);
}
}
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
基于XML配置集成Spring Session
- 启用注解配置RedisHttpSessionConfiguration、JedisConnectionFactory Bean
<context:annotation-config />
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration" />
<bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="172.16.31.84" />
<property name="port" value="6379" />
</bean>
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
- 配置web.xml加入DelegatingFilterProxy
<!-- Spring Context 配置 -->
<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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
Spring Session RESTFul APIs
Spring Session 支持RESTFul APIS,响应头回返回x-auth-token,来标识当前session的token。
基于Java 代码配置集成Spring Session 支持RESTFul APIs
需要Spring Session多配置一个HttpSessionStrategy bean
@Bean
public HttpSessionStrategy httpSessionStrategy() {
HeaderHttpSessionStrategy headerHttpSessionStrategy = new HeaderHttpSessionStrategy();
headerHttpSessionStrategy.setHeaderName("Auth-Token");
return headerHttpSessionStrategy;
}