SpringBoot + SpringSession + Redis Distributed Session solutions

SpringBoot + Redis Distributed Session solutions

Foreword

Scene:
When we set up a project application cluster, will have a session sharing problem. Because the session is stored in the server above.
Solution:
A one ip binding is achieved (by ip server binding one of them, there is no concept of a cluster) by the nginx load balancing;. B
implemented by cookie backup session (because the cookie data stored in the client. Therefore unsafe);
. C achieved (reliable) by redis backup the session;

SpringBoot + springsession + redis to achieve sharing session

Note: Before you set up redis server

1, pom introduced

        <!--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>

2, profile configuration

# Redis settings
spring.redis.database=2
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.ssl=false
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=100
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=
spring.session.store-type=redis

3, write controller

   @RequestMapping(value = "user/session")
    public BaseResult session(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 BaseResult.success(ResultCode.SUCCESS, userId);
    }

4, maven package the project

mvn clean package -Dmaven.skip.test=true

5, start the project twice, each with a different port

进入target目录启动项目,指定不同的端口
java -jar xxx_xxx.jar --server.port=8080
java -jar xxx_xxx.jar --server.port=8081

6, demonstration effect

分别访问,查看效果:
http://127.0.0.1:8080/user/session
http://127.0.0.1:8081/user/session

Guess you like

Origin blog.csdn.net/qq_33029793/article/details/92587980