likes
comments
collection
share

SpringBoot2.x系列教程44--SpringBoot中实现分布式的Session共享

作者站长头像
站长
· 阅读数 16

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第18天,点击查看活动详情

前言

在上一篇文章中,壹哥 给大家介绍了Session的理论知识,尤其是Session在分布式环境中存在的问题,那么这些问题该如何解决呢?接下来 壹哥 就在SpringBoot中通过一个代码案例,教会大家该如何实现Session共享功能。

一. SpringBoot中实现Session共享

1. 创建Web项目

我们按照之前的经验,创建一个Web程序,并将之改造成Spring Boot项目,具体过程略。 SpringBoot2.x系列教程44--SpringBoot中实现分布式的Session共享

2.添加依赖包

在项目的pom.xml文件中添加如何核心依赖包。

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

3.创建application.yml文件

创建一个application.yml文件,在其中添加如何核心配置。

server:
  port: 8080
#配置redis
spring:
  redis:
    host: 127.0.0.1
    port: 6379
    #password: 123456
    jedis:
      pool:
        max-idle: 8
        min-idle: 0
        max-active: 8
        #max-wait: 60000
    #timeout: 3000 #超时一定要大于0
  session:
    #设置session存储类型
    store-type: redis

这里可以设置多种session的store-type:

SpringBoot2.x系列教程44--SpringBoot中实现分布式的Session共享

我们这里选择利用redis来对session进行集中存储,实现session共享。

4. 创建Session配置类

package com.yyg.boot.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/4/28
 * @Description 开启Redis Http Session
 */
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600)
public class RedisHttpSessionConfiguration {

}

在这里添加@EnableRedisHttpSession注解,可以通过maxInactiveIntervalInSeconds属性设置Session的过期时间。

5. 创建一个Controller接口方法

该接口方法当用户不存在时提示“用户不存在”,否则会提示“用户存在”。

package com.yyg.boot.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/4/28
 * @Description Description
 */
@Slf4j
@RestController
public class SessionController {

    @RequestMapping("/session")
    public Object springSession(@RequestParam("username") String username, HttpServletRequest request, HttpSession session) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                log.warn(cookie.getName() + "=" + cookie.getValue());
            }
        }

        Object value = session.getAttribute("username");
        if (value == null) {
            log.warn("用户不存在");
            //保存session
            session.setAttribute("username", "{username: '" + username + "', age: 30}");
        } else {
            log.warn("用户存在");
        }

        return "username=" + value;
    }

}

6. 创建入口类

最后我们创建一个项目的入口类,方便进行项目启动。

package com.yyg.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/4/28
 * @Description Description
 */
@SpringBootApplication
public class SpringSessionApplication {

    public static void main(String[] args){
        SpringApplication.run(SpringSessionApplication.class,args);
    }

}

7. 完整项目结构

大家可以参考下图创建以上代码。

SpringBoot2.x系列教程44--SpringBoot中实现分布式的Session共享

二. 启动项目进行测试

1. 第一次访问测试

第一次在浏览器中进行访问,会看到浏览器中的username=null,并且控制台中展示的log信息为“用户不存在”,说明此时还没有创建出session。但是当第一次访问之后,session就被创建出来了,并且被存储到了redis中,实现了持久化存储。可以看如下图: SpringBoot2.x系列教程44--SpringBoot中实现分布式的Session共享

2. 第二次访问测试

第二次访问,就会看到username已经可以获取到新的信息了。 SpringBoot2.x系列教程44--SpringBoot中实现分布式的Session共享

log控制台中也看到已经提示“用户存在”的信息了。

SpringBoot2.x系列教程44--SpringBoot中实现分布式的Session共享

并且我们可以看到Redis控制台中,提示了TTL过期时间是3660,每隔1秒钟刷新1次,3600秒后过期。 SpringBoot2.x系列教程44--SpringBoot中实现分布式的Session共享

此时我们可以分别启动一个8080和8081进程,在两个进程上分别测试session接口。

#进入到项目的target目录下,执行java -jar命令,部署我们的jar包

F:\onlineWorks\boot-demos\demo43_springsession\target>java -jar demo43_springsession-1.0-SNAPSHOT.jar --server.port=8080

F:\onlineWorks\boot-demos\demo43_springsession\target>java -jar demo43_springsession-1.0-SNAPSHOT.jar --server.port=8081

SpringBoot2.x系列教程44--SpringBoot中实现分布式的Session共享

在浏览器中,我们的8080和8081端口上访问时,可以看到有一个共同的Session信息: SpringBoot2.x系列教程44--SpringBoot中实现分布式的Session共享

可以看到在两个不同的进程端口上,都分别访问到了同一个session信息,说明我们实现了分布式进程中session共享。可见在有了Spring Session后,实现session共享还是很简单得到。

结语

至此,壹哥 就带大家实现了分布式的Session共享功能,现在你学会了吗?如果你还有什么问题,可以在评论区留言给我。