Spring boot + redis realizes session sharing

This time I bring a tutorial on spring boot + redis to achieve session sharing.

 

In the spring boot documentation, we are told to add @EnableRedisHttpSession to enable spring session support. The configuration is as follows:

Java code  
@Configuration  
@EnableRedisHttpSession  
public class RedisSessionConfig {  
}
 

The annotation @EnableRedisHttpSession is provided by spring-session-data-redis, so add it in the pom.xml file:

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

 

Next, you need to configure the location of the redis server in application.properties. Here, we use this machine:

spring.redis.host=localhost  
spring.redis.port=6379
 

In this way, the simplest spring boot + redis to achieve session sharing is completed, and the next test is performed.

 

First, we open two tomcat services, the ports are 8080 and 9090, and set them in application.properties    :

server.port=8080
 

 

Next define a Controller: 

 
 
@RestController  
@RequestMapping(value = "/admin/v1")  
public class QuickRun {  
    @RequestMapping(value = "/first", method = RequestMethod.GET)  
    public Map<String, Object> firstResp (HttpServletRequest request){  
        Map<String, Object> 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<String, Object> map = new HashMap<>();  
        map.put("sessionId", request.getSession().getId());  
        map.put("message", request.getSession().getAttribute("map"));  
        return map;  
    }  
} 
 

启动之后进行访问测试,首先访问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并没有进行主从、读写分离等等配置(_(:з」∠)_其实是博主懒,还没尝试过.......)

而且,nginx的单点故障也是我们应用的障碍......以后可能会有对此次博客的改进版本,比如使用zookeeper进行负载均衡,敬请期待。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326529916&siteId=291194637