spring boot整合使用redis实现session共享

spring boot整合使用redis实现session共享

引入依赖

新建gradle的spring boot应用

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    compile group: 'org.springframework.session', name: 'spring-session-data-redis', version: '2.1.1.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.1.1.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-redis', version: '2.1.1.RELEASE'

    compileOnly 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

修改application.yml配置文件:

spring:
  application:
    name: redis-session
  redis:
    host: 127.0.0.1
    port: 6379
  session:
    store-type: redis


server:
  port: 8080
  # port: 8081

获取session

@RestController
public class SpringRedisSessionController {


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

    @RequestMapping(value = "/getSession", method = RequestMethod.GET)
    public Map<String, Object> getSession(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        map.put("port", port);
        map.put("session_id", request.getSession().getId());
        return map;
    }

}

分别启动端口为80808081的两个boot实例,在浏览器分别访问: http://localhost:8080/getSessionhttp://localhost:8081/getSession,
可以看到当访问http://localhost:8080/getSession时返回:

{
    "port": 8080,
    "session_id": "929bf507-e380-4e9d-bd1f-6e6fe5075aa2"
}

而当访问http://localhost:8081/getSession时返回:

{
    "port": 8081,
    "session_id": "929bf507-e380-4e9d-bd1f-6e6fe5075aa2"
}

可以发现不同实例返回的session_id是相同的,即实现了session共享的效果

后序

在访问/getSession请求的时候,可以发现在redis服务器中已经写入数据:

localhost:6379> keys *
1) "spring:session:sessions:expires:929bf507-e380-4e9d-bd1f-6e6fe5075aa2"
2) "spring:session:sessions:929bf507-e380-4e9d-bd1f-6e6fe5075aa2"
3) "spring:session:expirations:1547091540000"

猜你喜欢

转载自blog.csdn.net/u013887008/article/details/86286840
0条评论
添加一条新回复