版本
springboot:各分布式项目版本最好一样。
redis:5.0.5,单机。
源码
https://gitee.com/gbkill/springsession.git
代码
pom.xml
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--session-->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
application.properties
# Redis settings
spring.redis.database=0
spring.redis.host=192.168.100.11
spring.redis.port=6379
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=100
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=3000
# 存储方式
spring.session.store-type=redis
接口
package com.example.springsession.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
@RestController
@Slf4j
public class HelloCo {
@RequestMapping("/hello")
public String hello(HttpServletRequest request) {
String userId = (String) request.getSession().getAttribute("userId");
if (StringUtils.isEmpty(userId)) {
log.info("用户session_id为空!");
request.getSession().setAttribute("userId", "001_lxf");
} else {
log.info("用户session_id:" + userId);
}
return userId + "ssss " + request.getSession().getId();
}
}
测试
1. 打包项目
2. 启动两个项目
java -jar xxx --server.port=8081
java -jar xxx --server.port=8082
3. 先后访问
4. redis中存储