一、使用Redis存儲分布式session:
1.SpringBoot整合Redis,見如下地址:
JavaEE:SpringBoot整合Redis_a526001650a-CSDN博客
2.代碼實現分布式session存儲(此處以token為例):
@Autowired
private RedisTemplate<String, String> redisTemplate; //Redis數據操作類//登錄接口,存儲token到redis中
@PostMapping("/login")
public Response login(String phone, String code, HttpServletRequest request, HttpServletResponse response) {//...省略驗證手機號/驗證碼邏輯//1.根據手機號從庫中查出用戶信息User user = ...;//2.生成tokenString token = jwtUtil.genToken(String userNo, String phone);user.setToken(token);//3.1.緩存token到redis中redisTemplate.opsForValue().set("USER_TOKEN" + ":" + user.getId(), token);//3.2.緩存用戶信息到cookie中Cookie c = new Cookie("USER", gson.toJson(user));c.setMaxAge(時間); //設置最大有效期c.setDomain("yyh.com");c.setPath("/");response.addCookie(c);return Response.ok(user); //返回登錄成功
}//退出登錄接口,移除redis中的token
@PostMapping("/logout")
public Response logout(@RequestParam String userId, HttpServletRequest request, HttpServletResponse response) {//...省略獲取/驗證token邏輯//1.清除redis中的tokenredisTemplate.delete("USER_TOKEN" + ":" + userId);//2.清除cookie中tokenCookie c = new Cookie("USER", null);c.setDomain("yyh.com");c.setPath("/");c.setMaxAge(0); //設置過期時間為0(設為已過期)response.addCookie(c);return Response.ok(); //返回退出登錄成功
}
二、使用Spring Session存儲分布式session:
1.導入spring session與spring安全框架依賴:
<!-- 導入spring session -->
<dependency><groupId>org.springframework.session</groupId><artifactId>spring-session-data-redis</artifactId><version>3.5.1</version>
</dependency>
<!-- 導入spring安全框架 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId><version>3.5.3</version>
</dependency>
2.配置spring-session使用redis存儲,在application.yml中:
spring:session: #配置spring-session使用redis存儲store-type: redis
3.代碼實現分布式session存儲(此處以token為例):
(1)在Application中開啟基于redis的httpsesion:
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class}) //免除spring-session存儲key時要求登錄
@EnableRedisHttpSession ?//開啟基于redis的httpsesion
public class Application { //啟動類public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
(2)使用spring-session存儲分布式token:
//登錄接口,保存token到SpringSession中
@PostMapping("/login")
public Response login(String phone, String code, HttpServletRequest request, HttpServletResponse response) {//...省略驗證手機號/驗證碼邏輯//1.根據手機號查出用戶信息User user = ...;//2.生成tokenString token = jwtUtil.genToken(String userNo, String phone);user.setToken(token);//3.保存token到SpringSession中HttpSession hs = request.getSession();hs.setAttribute("USER_TOKEN" + ":" + user.getId(), token);hs.setMaxInactiveInterval(30 * 24* 60 * 60); //超時時間//...省略緩存用戶信息到cookie中return Response.ok(user); //返回登錄成功
}//登出接口,移除SpringSession中token
@PostMapping("/logout")
public Response logout(@RequestParam String userId, HttpServletRequest request, HttpServletResponse response) {//...省略獲取/驗證token邏輯//1.清除Spring Session中的tokenHttpSession hs = request.getSession();hs.removeAttribute("USER_TOKEN" + ":" + userId); //刪除指定用戶token//...省略清除cookie中tokenreturn Response.ok(); //返回退出登錄成功
}