springboot+redis集群实现redis集群状态下的session共享

springboot+redis的案例很多,但是redis集群的案例很少,so~笔者在这里记录一下~


一、springboot依靠@EnableRedisHttpSession来开启spring session支持,该注解是由spring-session-data-redis提供的,所以在pom.xml文件中添加如下依赖:

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

二、配置@EnableRedisHttpSession来开启spring session支持

方法一:在springboot启动类上加上@EnableRedisHttpSession来开启spring session支持,其中maxInactiveIntervalInSeconds 的值是session过期时间

方法二:重建redisSession管理类,加上EnableRedisHttpSession配置

@Configuration  

@EnableRedisHttpSession  (maxInactiveIntervalInSeconds = 1800)

public class RedisSessionConfig { 


} 

三、在配置文件(application.properties文件或者yaml文件)中配置redis服务器的位置

spring.redis.cluster.nodes=Centos6701:6379,Centos6701:6380,Centos6702:6380,Centos6702:6379,Centos6703:6380,Centos6703:6379
yaml:
 spring:  
   redis:  
     cluster:  
       nodes:  
        - Centos6701:6379  
        - Centos6701:6380
        - Centos6702:6380
        - Centos6702:6379 
        - Centos6703:6379 
        - Centos6703:6380

四、测试

1、 首先在application.properties中进行设置开启两个tomcat服务,端口分别为8080和9090

2、定义一个Controller

@RestController  

@RequestMapping(value = "/admin/v1")  

public class QuickRun {  


    @RequestMapping(value = "/first", method = RequestMethod.GET)  

    public Map firstResp (HttpServletRequest request){  


        Map map = new HashMap<>();  

        request.getSession().setAttribute("request Url", request.getRequestURL());  

        map.put("request Url", request.getRequestURL());  

        return map;  

    }  

 
    @RequestMapping(value = "/sessions", method = RequestMethod.GET)  

    public Object sessions (HttpServletRequest request){  


        Map map = new HashMap<>();  

        map.put("sessionId", request.getSession().getId());  

        map.put("message", request.getSession().getAttribute("map"));  

        return map;  
    }  

} 

    3、启动之后进行访问测试,首先访问8080端口的tomcat,返回

{"request Url":"http://localhost:8080/admin/v1/first"}

接着访问8080端口的sessions,返回

{"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:8080/admin/v1/first"}

最后访问9090端口的sessions,返回

{"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:8080/admin/v1/first"}

可见,8080与9090两个服务器返回结果一样,实现了session的共享

  如果此时再访问9090端口的first的话,首先返回:

{"request Url":"http://localhost:9090/admin/v1/first"} 

而两个服务器的sessions都是返回:

{"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:9090/admin/v1/first"} 

  通过spring boot + redis来实现session的共享非常简单,而且用处也极大,配合nginx进行负载均衡,便能实现分布式的应用了。

本次的redis并没有进行主从、读写分离、使用zookeeper进行负载均衡等等配置,而且nginx的单点故障也是应用的障碍。

参考文档:

https://www.cnblogs.com/mengmeng89012/p/5519698.html

https://blog.csdn.net/qq_32143169/article/details/78183325

https://blog.csdn.net/qq_32143169/article/details/78183263

你可能感兴趣的:(springboot+redis集群实现redis集群状态下的session共享)