1.添加Maven依赖
org.apache.commons
commons-pool2
2.5.0
redis.clients
jedis
org.springframework.boot
spring-boot-starter-data-redis
io.lettuce
lettuce-core
org.springframework.session
spring-session-data-redis
2.自定义RedisConfig
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.timeout}")
private int timeout;
@Bean
public JedisPool redisPoolFactory() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
return new JedisPool(jedisPoolConfig, host, port, timeout, password);
}
@Bean(name = "redisTemplate")
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
objectMapper.enableDefaultTyping(DefaultTyping.NON_FINAL);
Jackson2JsonRedisSerializer
3.自定义RedisSessionConfig
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 300)
public class RedisSessionConfig {
}
4.定义测试Controller
@RestController
public class TestController {
@RequestMapping(value = "/sessionInfo", method = RequestMethod.GET)
public Map addSession (HttpServletRequest request){
String sessionId = request.getSession().getId();
String requestURI = request.getRequestURI();
Map sessionInfoMap = new HashMap<>(2);
sessionInfoMap.put("sessionId", sessionId);
sessionInfoMap.put("requestURI", requestURI);
return sessionInfoMap;
}
}
5.测试
开启2台tomcat(域名要相同 端口可以不同),同一个浏览器session共享 具体可以看sessionId值
源码 https://gitee.com/jsjack_wang/springboot-demo dev-redis-session分支