1 Conventional way
The following redisOperator
is a tool class, which simply encapsulates the redis api operation. If you are interested, you can download it at the following address:
CSDN download address : https://download.csdn.net/download/qq_15769939/15378282
1.1 Login
// 登录的时候,token存入redis
String uniqueToken = UUID.randomUUID().toString().trim();
redisOperator.set("redis_user_token" + ":" + userId,uniqueToken);
1.2 Exit
// 退出的时候,redis中移除token
String uniqueToken = UUID.randomUUID().toString().trim();
redisOperator.del("redis_user_token" + ":" + userId);
2 springSession way
2.1 Introduce dependencies
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.2 Configure storage type
spring:
session:
store-type: redis
2.3 boot configuration
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class}) // 去除安全自动装配
@EnableRedisHttpSession // 开启使用redis作为spring session
2.4 Sample code
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* 类文件: TestController
* <p>
* <p>
* 类描述:测试控制层
* <p>
* 作 者: AusKa_T
* <p>
* 日 期: 2021/1/20 0010
* <p>
* 时 间: 20:19
* <p>
*/
@RestController
public class TestController {
@GetMapping("/setSession")
public Object setSession(HttpServletRequest request) {
HttpSession session = request.getSession();
session.setAttribute("userInfo","new User");
session.setMaxInactiveInterval(3600);
session.getAttribute("userInfo");
// session.removeAttribute("userInfo");
return "ok";
}
2.5 Testing
Access address interface setSession
, redis客户端
view data in
3 Related information
- The blog post is not easy, everyone who has worked so hard to pay attention and praise, thank you