Home  >  Article  >  Java  >  An introduction to how to use Spring Session and redis to share Sessions

An introduction to how to use Spring Session and redis to share Sessions

巴扎黑
巴扎黑Original
2017-09-06 09:24:561745browse

This article mainly introduces you to the relevant information about using Spring, Session and redis to share Session. The article introduces it in great detail through sample code. It has certain reference learning value for everyone's study or work. It is needed Friends, please follow the editor to learn together.

Preface

After we set up the cluster environment, one issue we have to consider is how to handle the sessions generated by user access.

There are many ways to process sessions. For details, please see the previous blog reprinted: 5 session processing strategies in cluster/distributed environments

Here We discuss the third method: session sharing.

The redis cluster performs master-slave replication and uses the eventual consistency of the redis database to store session information in redis. When the application server finds that the session is not in the local memory, it searches it in the redis database. Because the redis database is a database independent of the application server, the session can be shared and highly available.

Disadvantages:

1.redis requires a large memory, otherwise the user session will be cleared from the Cache.

2. The cache needs to be refreshed regularly

The preliminary structure is as follows:


## However, there are still problems with this structure. The redis master is an important bottleneck. If the master crashes, redis will not actively perform master switching, and the session service will be interrupted.

But let’s create this structure first, and then optimize and modify it later.

Spring Boot provides Spring Session to complete session sharing.

Official documentation: http://docs.spring.io/spring-session/docs/current/reference/html5/guides/boot.html#boot-sample

First create a simple Controller:


@Controller 
public class UserController { 
 
 @RequestMapping(value="/main", method=RequestMethod.GET) 
 public String main(HttpServletRequest request) { 
 HttpSession session = request.getSession(); 
 String sessionId = (String) session.getAttribute("sessionId"); 
 if (null != sessionId) { // sessionId不为空 
 System.out.println("main sessionId:" + sessionId); 
 return "main"; 
 } else { // sessionId为空 
 return "redirect:/login"; 
 } 
 } 
 
 
 @RequestMapping(value="/login", method=RequestMethod.GET) 
 public String login() { 
 return "login"; 
 } 
 
 @RequestMapping(value="/doLogin", method=RequestMethod.POST) 
 public String doLogin(HttpServletRequest request) { 
 System.out.println("I do real login here"); 
 HttpSession session = request.getSession(); 
 String sessionId = UUID.randomUUID().toString(); 
 session.setAttribute("sessionId", sessionId); 
 System.out.println("login sessionId:" + sessionId); 
 return "redirect:/main"; 
 } 
}

To put it simply, it is to simulate permission control. If the sessionId exists, access the homepage, otherwise it will jump. Go to the login page.

So how to achieve session sharing?

Add the following dependencies:


<!-- spring session --> 
<dependency> 
 <groupId>org.springframework.session</groupId> 
 <artifactId>spring-session</artifactId> 
 <version>1.3.0.RELEASE</version> 
</dependency> 
<!-- redis --> 
<dependency> 
 <groupId>org.springframework.boot</groupId> 
 <artifactId>spring-boot-starter-redis</artifactId> 
</dependency>

Add configuration class:


@EnableRedisHttpSession 
public class HttpSessionConfig { 
 @Bean 
 public JedisConnectionFactory connectionFactory() { 
 return new JedisConnectionFactory(); 
 } 
}

What is the use of this configuration class?

Official documentation:

The Spring configuration is responsible for creating a Servlet Filter that replaces the HttpSession implementation with an implementation backed by Spring Session.


In other words, this configuration class can create a filter that supports Spring Session to function instead of HttpSession.

The @EnableRedisHttpSession annotation creates a Spring Bean with the name of springSessionRepositoryFilter that implements Filter. The filter is what is in charge of replacing the HttpSession implementation to be backed by Spring Session. In this instance Spring Session is backed by Redis.

@EnableRedisHttpSession annotation will create a bean object of springSessionRepositoryFilter to implement this filter. Filter is responsible for replacing HttpSession.

In other words,

HttpSession no longer plays a role, but uses redis to directly operate the Session through the filter.

Add redis configuration in application.properties:


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

In this way, Session sharing is completed. Is not it simple? The business code doesn't even need a little modification.


Verification:

The redis database is empty at first.

Run the project:

After accessing the page, you can see the session information in redis.

After logging in casually:

Enter the main. It means that sessionId exists in the current session.

We check the cookies of the current page. In other words, this cookie has sessionId.


#Run a new project with the port 8081. Open a new tab directly in the original browser. We know that the cookie is shared at this time. Visit localhost:8081/main


We directly accessed the new project successfully! ! The same cookie can be used to share sessions in different web servers.

Finally emphasize again:

The implementation of HttpSession is replaced by Spring Session. Operating HttpSession is equivalent to operating data in redis.

The above is the detailed content of An introduction to how to use Spring Session and redis to share Sessions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn