在spring mvc中利用spring-session+redis实现分布式session

背景

  平时部署项目过程中可能会遇到一个程序发布到多台服务器上,通过Nginx代理请求的情况,那么某个用户在一台服务器上登录成功过后,就不用在其他服务器上再登录了,这个时候就需要用到今天说的东西了。

1、maven包添加

 1 
 2     org.springframework.session
 3     spring-session-data-redis
 4 1.2.1.RELEASE
 5 
 6 
 7 
 8 org.springframework.session
 9     spring-session
10     1.2.1.RELEASE
11 

2、在spring-redis.xml中添加,其中重写RedisSerializer文件,可以点击这里查看

 1 
 2      3         class="org.springframework.data.redis.serializer.StringRedisSerializer" />
 4      5         class="centaline.small.course.tool.GenericFastJson2JsonRedisSerializer" />
 6      7         class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
 8         
 9         
10     
11     12         class="xx.xx.xx.xx.xx (重写RedisSerializer文件路径)" />
13 
14     15         class="org.springframework.session.web.http.DefaultCookieSerializer">  
16           
17           
18       
19            
20      21         class="org.springframework.session.web.http.CookieHttpSessionStrategy">  
22           
23      

3、在登录成功后设置session和平时一样,附上工具类。

 1 public class SessionUtils {
 2 
 3     @Resource(name = "sessionRepository")
 4     private SessionRepository sessionRepository;
 5 
 6     private static final String SESSION_NAME = "LOGIN_INFO_SESSION";
 7 
 8     @Autowired
 9     private HttpSession httpSession;
10 
11     public String getSessionId() {
12         String sessionId = httpSession.getId();
13         return sessionId;
14     }
15 
16     public LoginInfo getLoginInfo() {
17         LoginInfo loginInfo = (LoginInfo) httpSession.getAttribute(SESSION_NAME);
18         return loginInfo;
19     }
20 
21     public String setLoginInfo(LoginInfo loginInfo) {
22         String sessionId = httpSession.getId();
23         httpSession.setAttribute(SESSION_NAME, loginInfo);
24         return sessionId;
25     }
26 
27     public void logout() {
28         httpSession.removeAttribute(SESSION_NAME);
29     }
30 
31     public LoginInfo getLoginInfoBySessionId(String sessionId) {
32         ExpiringSession expiringSession = sessionRepository.getSession(sessionId);
33         LoginInfo loginInfo = (LoginInfo) expiringSession.getAttribute(SESSION_NAME);
34         return loginInfo;
35     }
36 }
SessionUtils

 

转载于:https://www.cnblogs.com/rolayblog/p/11176433.html

你可能感兴趣的:(java,数据库,测试)