springboot2整合spring-session-data-redis,实现session共享

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 jsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        jsonRedisSerializer.setObjectMapper(objectMapper);
        redisTemplate.setDefaultSerializer(jsonRedisSerializer);

        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

application.properties关于Redis配置
spring.redis.host=182.92.234.232
spring.redis.port=6379
spring.redis.password=
spring.redis.timeout=2000
 
  

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分支

你可能感兴趣的:(springboot2整合spring-session-data-redis,实现session共享)