springboot +springsession+redis 做session共享

版权声明:本文为博主原创文章,欢迎转载,转载请注明作者、原文超链接

springboot版本 2.0.5.RELEASE
maven:

 
      org.springframework.boot
      spring-boot-starter-data-redis
  
  
      org.springframework.session
      spring-session-data-redis
  

启动类:

@SpringBootApplication
@ComponentScan(value = "com.qjs.*")
@EnableRedisHttpSession
public class CollectionApplication {

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

controller:

@RestController
public class SessionShare {
	//模拟登陆
    @ResponseBody
    @RequestMapping(value = "/Login",method = RequestMethod.GET)
    public String Login(HttpServletRequest request) {
        request.getSession().setAttribute("username","ethan");
        return request.getSession().getId();
    }
    @ResponseBody
    @RequestMapping(value = "/getSession",method = RequestMethod.GET)
    public String getSession(HttpServletRequest request) {
        return request.getSession().getAttribute("username")+"@@"+ request.getSession().getId();
    }
}

此时最简版项目搭建完毕,拷贝项目,分别启动这两个项目,端口分别为8080,9090

先模拟登陆
http://localhost:8080/Login
返回sessionId:eb30fc4b-fff3-408e-bbf9-20ae9e9a9c7c
再访问:http://localhost:8080/getSession
返回:ethan@@eb30fc4b-fff3-408e-bbf9-20ae9e9a9c7c

访问9090端口的项目

http://localhost:9090/getSession
返回:ethan@@eb30fc4b-fff3-408e-bbf9-20ae9e9a9c7c

查看redis
不要用keys*(阻塞),用scan命令(非阻塞)

xxxx:8001> scan 0 match *session* count 10
1) "0"
2) 1) "spring:session:sessions:expires:eb30fc4b-fff3-408e-bbf9-20ae9e9a9c7c"
xxxx:8001> 

完成的session共享

你可能感兴趣的:(springboot +springsession+redis 做session共享)