官方文档地址:http://projects.spring.io/spring-session/
http://docs.spring.io/spring-session/docs/current/reference/html5/guides/httpsession.html
Spring Session为企业级Java应用的session管理带来了革新,使得以下的功能更加容易实现:
<dependency> <groupId>org.springframework.sessiongroupId> <artifactId>spring-session-data-redisartifactId> <version>1.2.2.RELEASEversion> <type>pomtype> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webartifactId> <version>4.2.5.RELEASEversion> dependency>
HttpSessionConfig:
//maxInactiveIntervalInSeconds为session过期时间,这里注意session过期时间配置在web.xml里面是不起作用的 @Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds=999) public class HttpSessionConfig { //这里有个小坑,如果服务器用的是云服务器,不加这个会报错 @Bean public static ConfigureRedisAction configureRedisAction() { return ConfigureRedisAction.NO_OP; } //这里是reids连接配置 @Bean public JedisConnectionFactory connectionFactory() { JedisConnectionFactory connection = new JedisConnectionFactory(); connection.setPort(6379); connection.setHostName("127.0.0.1"); connection.setPassword("ps123456"); connection.setDatabase(8); return connection; } //session策略,这里配置的是Header方式(有提供Header,COOKIE等方式),可自定义,后面会详细讲 @Bean public HttpSessionStrategy httpSessionStrategy() { return new HeaderHttpSessionStrategy(); } }
Initializer:
public class Initializer extends AbstractHttpSessionApplicationInitializer { }
public class HeaderHttpSessionStrategy implements HttpSessionStrategy { private String headerName = "x-auth-token"; public String getRequestedSessionId(HttpServletRequest request) { return request.getHeader(this.headerName); } public void onNewSession(Session session, HttpServletRequest request, HttpServletResponse response) { response.setHeader(this.headerName, session.getId()); } public void onInvalidateSession(HttpServletRequest request, HttpServletResponse response) { response.setHeader(this.headerName, ""); } /** * The name of the header to obtain the session id from. Default is "x-auth-token". * * @param headerName the name of the header to obtain the session id from. */ public void setHeaderName(String headerName) { Assert.notNull(headerName, "headerName cannot be null"); this.headerName = headerName; } }
public final class MapSession implements ExpiringSession, Serializable { /** * Default {@link #setMaxInactiveIntervalInSeconds(int)} (30 minutes). */ public static final int DEFAULT_MAX_INACTIVE_INTERVAL_SECOnDS= 1800; private String id; private MapsessiOnAttrs= new HashMap (); private long creatiOnTime= System.currentTimeMillis(); private long lastAccessedTime = this.creationTime; /** * Defaults to 30 minutes. */ private int maxInactiveInterval = DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS; /** * Creates a new instance with a secure randomly generated identifier. */ public MapSession() { this(UUID.randomUUID().toString()); } /** * Creates a new instance with the specified id. This is preferred to the default * constructor when the id is known to prevent unnecessary consumption on entropy * which can be slow. * * @param id the identifier to use */ public MapSession(String id) { this.id = id; }
public interface SessionRepositoryextends Session> { S createSession(); void save(S session); S getSession(String id); void delete(String id); }
public class MyHttpSessionStrategy implements HttpSessionStrategy { private final Logger logger = LoggerFactory.getLogger(WlwHttpSessionStrategy.class); //这用Qualifier注解,如果你的工程还集成了spring-data-redis,需要指定一下用哪一个 @Qualifier("sessionRedisTemplate") @Autowired private RedisTemplate redisTemplate; //过期时间,与session过期时间保持一致 private Long maxInactiveIntervalInSecOnds= 999L; private String xxxRedisName = "spring:session:xxx:"; //当客户端没有传xxx参数的时候,避免创建多个无用的session占用redis空间 private String defaultSessiOnId= "default-sessionid"; /** * 客户端传过来的是xxx,需要通过xxx查找映射关系,拿到sessionid返回 */ public String getRequestedSessionId(HttpServletRequest request) { String xxx = request.getParameter("xxx"); ValueOperationsvops = redisTemplate.opsForValue(); if (xxx != null && !xxx.equals("")) { String sessionid = vops.get(xxxRedisName + xxx); if(sessionid!=null){ redisTemplate.expire(xxxRedisName + xxx, maxInactiveIntervalInSeconds, TimeUnit.SECONDS); } return sessionid; } else { return vops.get(xxxRedisName+defaultSessionId); } } /** * 创建session时,保存xxx和sessionid的映射关系 */ public void onNewSession(Session session, HttpServletRequest request, HttpServletResponse response) { String xxx = request.getParameter("xxx"); String sessionid = session.getId(); ValueOperations vops = redisTemplate.opsForValue(); if (xxx != null && !xxx.equals("")) { //保存xxx和sessionid映射关系 vops.set(xxxRedisName + xxx, sessionid); redisTemplate.expire(xxxRedisName + xxx, maxInactiveIntervalInSeconds, TimeUnit.SECONDS); }else{ //没有传xxx时,保存为默认 vops.set(xxxRedisName+defaultSessionId, sessionid); redisTemplate.expire(xxxRedisName+defaultSessionId, maxInactiveIntervalInSeconds, TimeUnit.SECONDS); } } public void onInvalidateSession(HttpServletRequest request, HttpServletResponse response) { String xxx = request.getParameter("xxx"); redisTemplate.expire(xxxRedisName + xxx, 0, TimeUnit.SECONDS); } }
好了,完工了。。。