This is a tutorial to implement session sharing with spring boot + redis.
In the spring boot documentation, tell us to add @enableredishttpsession to enable spring session support, which is configured as follows:
-
@Configuration
-
@EnableRedisHttpSession
-
public class redissessionconfig {
-
}
and @enableredishttpsession This annotation 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, where we use this machine:
Spring.redis.host=localhost
spring.redis.port=6379
In this way, the simplest spring boot + REDIS Implementation session sharing is complete, below to test.
First we open two Tomcat services, with ports 8080 and 9090, set 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;
}
}
After starting the access test, first access 8080-port Tomcat, return to get "" :
{"request Url":"Http://localhost:8080/admin/v1/first"}
Next, we visit the 8080 port of sessions and return:
-
{ "SessionId": "message":
Finally, access to port 9090, sessions, returns:
-
{ "SessionId": "message":
As can be seen, 8080 and 90,902 servers return the results, the realization of the session sharing
If you are accessing the first of Port 9090 at this point, return:
{"request Url":"Http://localhost:9090/admin/v1/first"}
The sessions of two servers are returned:
-
{ "SessionId": "message":
Using spring boot + Redis to achieve session sharing is very simple and useful, with nginx load balancing, you can achieve distributed applications.
This time Redis does not carry out the master-slave, read-write separation and so on configuration (_ (: З"∠) _ is actually Bo Master lazy, has not tried ...)
Moreover, Nginx single point of failure is also a barrier to our application ... There may be an improved version of this blog later, such as load balancing with zookeeper, so please look forward to it.
Spring Boot + Redis implementation session sharing