新建spring-boot项目
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
SpringSessionApplication.java
@RestController
@SpringBootApplication
public class SpringSessionApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSessionApplication.class, args);
}
@RequestMapping("/session")
public Integer test(HttpServletRequest req) {
Integer count = (Integer) req.getSession().getAttribute("count");
if (count == null) {
count = 0;
}
req.getSession().setAttribute("count", count + 1);
System.out.println(count);
return count;
}
}
application.properties 需要添加:
spring.session.store-type=redis
启动 redis-server.exe, 运行应用,然后访问 http://127.0.0.1:8080/session。即使服务重启,session也不会丢失了。