spring Session 提供了一套用于管理用户 session 信息的API和实现。
Spring Session为企业级Java应用的session管理带来了革新,使得以下的功能更加容易实现:
Spring-Boot集成Spring session并存入redis
添加maven依赖
Redis的相关依赖可以看之前的内容,这里需要增加如下依赖。
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
</dependency>
Java代码实现
增加HttpSessionConfig。
package com.core.config;
import org.springframework.context.annotation.Bean;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.HeaderHttpSessionStrategy;
import org.springframework.session.web.http.HttpSessionStrategy;
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 100, redisNamespace = "xxxx")
public class HttpSessionConfig {
@Bean
public HttpSessionStrategy httpSessionStrategy() {
return new HeaderHttpSessionStrategy();
}
}
其中注解 EnableRedisHttpSession 创建了一个名为springSessionRepositoryFilter的Spring Bean,该Bean实现了Filter接口。该filter负责通过 Spring Session 替换HttpSession从哪里返回。这里Spring Session是通过 redis 返回。
类中的方法 httpSessionStrategy(),用来定义Spring Session的 HttpSession 集成使用HTTP的头来取代使用 cookie 传送当前session信息。如果使用下面的代码,则是使用cookie来传送 session 信息。
@Bean
public HttpSessionStrategy httpSessionStrategy() {
return new CookieHttpSessionStrategy();
}
使用HTTP的头,会看到如下信息
-- response --
200
x-auth-token: 4792331e-44c2-4285-a9d1-ebabf0e72251
Content-Type: text/html;charset=UTF-8
Content-Length: 75
Date: Mon, 09 Jan 2017 10:14:00 GMT
8e107efb-bf1e-4a55-b896-c97f629c8e40 : 4792331e-44c2-4285-a9d1-ebabf0e72251
使用cookie,会看到如下信息
-- response --
200
Set-Cookie: SESSION=4792331e-44c2-4285-a9d1-ebabf0e72251;path=/;HttpOnly
Content-Type: text/html;charset=UTF-8
Content-Length: 75
Date: Mon, 09 Jan 2017 10:47:37 GMT
测试
在controller中增加如下代码
@GetMapping("/")
public String uid(HttpServletRequest request) {
HttpSession session = request.getSession();
UUID uid = (UUID) session.getAttribute("uid");
if (uid == null) {
uid = UUID.randomUUID();
}
session.setAttribute("uid", uid);
return uid.toString() + " : " + session.getId();
}
启动服务,在chrome浏览器输入 http://127.0.0.1:8080/,得到sessionId
fbfae849-1d49-4301-b963-573048e763e7
在redis中可以看到如下信息
1) "spring:session:xxxx:sessions:fbfae849-1d49-4301-b963-573048e763e7"
2) "spring:session:xxxx:expirations:1483958700000"
3) "spring:session:xxxx:sessions:expires:fbfae849-1d49-4301-b963-573048e763e7"
打开火狐的HttpRequester,使用chrome获取的sessionId点击Get,可以看到如下输出
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。