Redis 之 Session 共享

Redis 之 Session 共享

Scroll Down

Session 共享

HttpSession 是通过 Servlet 容器创建并进行管理的, 创建成功之后都是保存在内存中的.

Spring Boot 提供了自动化的Session共享配置, 它结合Redis可以非常方便的解决这个问题.

Session 共享配置

pom.xml

        <!-- Redis 排除Lettuce 引入Jedis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>

application.yml

  # redis 配置
  redis:
    database: 0
    host: www.iscolt.com
    port: 6379
    password: 5211
    jedis:
      pool:
        max-active: 8
        max-idle: 8
        max-wait: -1ms
        min-idle: 0

HelloController.java

/**
 * 共享Session
 *
 * @Auther: MaWenyi
 * @Date: 2019/6/30
 * @Description: work.idler.dtai.controller
 * @version: 1.0
 */
@Api(value = "Session 共享测试")
@RestController
public class HelloController {

    @Value("${server.port}")
    String port;

    @ApiOperation(value = "添加名字", notes = "根据参数添加名字")
    @PostMapping("/save")
    public String saveName(String name, HttpSession session) {
		// 将name加入session 实际上已经存到了Redis中
        session.setAttribute("name", name);
        return port;
    }

    @ApiOperation(value = "获取名字", notes = "根据name获取值")
    @GetMapping("/get")
    public String getName(HttpSession session) {
        return port + ":" + session.getAttribute("name").toString();
    }
}

注意: 这边整合了Swagger, 方便测试

支付宝 微信