SpringBoot利用Redis管理分布式Session

https://www.jianshu.com/p/fe9a6c3bda4e

1、添加pom配置

<dependencies>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>
</dependencies>

2、添加yml参数

spring:
  redis:
    cluster:
      nodes: X.X.X.X:6379
    password: XXXXXXXXXXXXXXX
    pool:
      max-active: 8
      max-idle: 8
      max-wait: -1
      min-idle: 0
    timeout: 5000
  session:
    redis:
      namespace: XXXXXXXXXXXXXX

3、添加Redis配置类

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600)
public class RedisSessionConfig {

    private static final Logger logger = LoggerFactory.getLogger(RedisSessionConfig.class);

    @Value("${spring.redis.cluster.nodes}")
    private String cluster;

    @Value("${spring.redis.password}")
    private String password;

    public RedisSessionConfig() {
        //redisSession配置类
    }

    @Bean
    public static ConfigureRedisAction configureRedisAction() {
        logger.info("redisconfig配置生效");
        return ConfigureRedisAction.NO_OP;
    }

    @Bean
    public JedisConnectionFactory connectionFactory() {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisClusterConfiguration(), jedisPoolConfig());
        jedisConnectionFactory.setPassword(password);
        jedisConnectionFactory.setUsePool(true);
        jedisConnectionFactory.setTimeout(1800);
        return jedisConnectionFactory;
    }

    /**
     * redis集群配置
     * 配置redis集群的结点及其它一些属性
     *
     * @return
     */
    private RedisClusterConfiguration redisClusterConfiguration() {
        RedisClusterConfiguration redisClusterConfig = new RedisClusterConfiguration();

        redisClusterConfig.setClusterNodes(getClusterNodes());

        redisClusterConfig.setMaxRedirects(3);
        return redisClusterConfig;

    }

    /**
     * JedisPoolConfig 配置
     * <p/>
     * 配置JedisPoolConfig的各项属性
     *
     * @return
     */
    private JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        //连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
        jedisPoolConfig.setBlockWhenExhausted(true);

        //是否启用pool的jmx管理功能, 默认true
        jedisPoolConfig.setJmxEnabled(true);

        //jedis调用returnObject方法时,是否进行有效检查
        jedisPoolConfig.setTestOnReturn(true);

        //是否启用后进先出, 默认true
        jedisPoolConfig.setLifo(true);

        //最大空闲连接数, 默认8个
        jedisPoolConfig.setMaxIdle(8);

        //最大连接数, 默认8个
        jedisPoolConfig.setMaxTotal(8);

        //获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
        jedisPoolConfig.setMaxWaitMillis(-1);

        //逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
        jedisPoolConfig.setMinEvictableIdleTimeMillis(3600000);

        //最小空闲连接数, 默认0
        jedisPoolConfig.setMinIdle(0);

        //每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
        jedisPoolConfig.setNumTestsPerEvictionRun(3);

        //对象空闲多久后逐出, 当空闲时间>该值 且 空闲连接>最大空闲数 时直接逐出,不再根据MinEvictableIdleTimeMillis判断  (默认逐出策略)
        jedisPoolConfig.setSoftMinEvictableIdleTimeMillis(3600000);

        //在获取连接的时候检查有效性, 默认false
        jedisPoolConfig.setTestOnBorrow(false);

        //在空闲时检查有效性, 默认false
        jedisPoolConfig.setTestWhileIdle(false);

        //逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
        jedisPoolConfig.setTimeBetweenEvictionRunsMillis(-1);
        return jedisPoolConfig;
    }

    /**
     * redis集群节点IP和端口的添加
     * <p/>
     * 节点:RedisNode redisNode = new RedisNode("127.0.0.1",6379);
     *
     * @return redis集群配置
     */
    private Set<RedisNode> getClusterNodes() {
        // 添加redis集群的节点
        logger.info("读取到的redis集群配置为:{}", cluster);
        if (!StringUtils.isBlank(cluster)) {
            Set<RedisNode> clusterNodes = new HashSet<>();
            List<String> nodes = Arrays.asList(cluster.split(","));
            for (String node : nodes) {
                List<String> domainAndPort = Arrays.asList(node.split(":"));
                String domain = domainAndPort.get(0);
                int port = Integer.parseInt(domainAndPort.get(1));
                clusterNodes.add(new RedisNode(domain, port));
            }
            return clusterNodes;
        } else {
            logger.error("redis集群配置为空!");
            return null;
        }
    }
}

4、添加session

request.getSession().setAttribute("user", result);

5、获取session

Object user = request.getSession().getAttribute("user");

相关推荐