Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of Cluster session sharing based on SpringSession+Redis

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

After WEB application development is completed, it is deployed to Tomcat or other containers for users to access. Small applications install Tomcat on a server and deploy WEB applications. As the number of visits increases, the pressure on Tomcat will increase until it crashes. In order to ensure the carrying capacity of WEB applications, it is necessary to cluster WEB applications.

With the development of technology today, cluster / load balancing has become relatively simple. Let's introduce these two concepts to beginners in popular language:

When a KFC opens, there is only one ordering window (a Tocmat server, which can save costs) to provide ordering service. There is no problem with daily ordering, there will be a long line at a window during meals or weekends. Not only does the customer complain (long response time to requests and poor user experience), but the waiter is also so tired that one day he gets tired (Tomcat hangs up).

At this time, a window (an additional Tomcat server) is added to the side to provide ordering service, but many customers do not know the new window, so there is still a long queue in the original window (users still visit the original Tomcat). At this time, a person needs to stand at the door to direct customers to which window to order according to the queuing situation of each window (load balancer). The purpose of this person is to keep the number of orders in each window roughly equal, so that some windows are busy and some are idle. As customers increase, so will the ordering window (more and more Tomcat).

Cluster: a group of servers come together to provide services. In the above example, multiple ordering windows (multiple Tomcat) provide ordering service together. Load balancing: keep the load of each ordering window (each Tomcat) in the cluster balanced and avoid one or more free spaces.

The two concepts appear at the same time, and there is no load balancing for services without clusters (single Tomcat). Without load balancing for clustered services, resources will be wasted.

There are many WEB load balancing schemes, and Nginx + Tomcat is one of the commonly used ones. Nginx acts as a load balancer to divert traffic according to the load of each Tomcat.

Each Tomcat is equivalent to an ordering window, and you can provide ordering service. Every time you want to order, you have to go through NginxNginx. According to the availability of each window, you will assign the user which window to order the first time to order in window 1, and then order again immediately after ordering. It is possible to be assigned to window 2.

Let's build the WEB application of load balancing.

1) build WEB application

Prepare the WEB application, deploy with two Tomcat, and return the Tomcat port number as a result in order to be able to distinguish which Tomcat is processing the request.

/ * * obtain the Tomcat port number of the deployment project * / @ RequestMapping ("/ port/get") @ ResponseBodypublic String getPort (HttpServletRequest request) {return String.valueOf (request.getLocalPort ());}

In this example, the project is deployed with two ports 5677 and 5688, respectively. Access / port/get request returns the port number with a result of Tomcat

Http:// localhost:5677/port/get

Http:// localhost:5688/port/get

2) Nginx configure load balancer

The installation of Nginx under Window is relatively simple. Students who will not install Baidu will briefly introduce the Nginx configuration file: nginx.conf

# number of Nginx processes # worker_processes events {# maximum number of concurrent links worker_connections 1024;} # configuration related to Nginx processing HTTP requests # http cannot be repeated, globally unique http {# virtual host, multiple virtual hosts can be configured # Nginx listens on 88Magneto 90 three ports, can be configured with three server server {# port numbers, access to port 88 will handle listen 88 according to the configuration under this server # Host name server_name localhost; # matches the URL according to the regular expression, and the matched URL is processed according to the configuration under the location # / represents the root directory where all requests for access to port 88 location / {# static resources are located, and will look for static resources from this directory # example: visit / a.html, find D:/a.html and return root location;}

The most basic Nginx configuration of the above configuration file will be handled by Nginx when we access http://localhost:88. Let's configure the load balancer of Nginx.

The two tomcat defined in configuration 1), add the following code under the http node:

# define server information that requires load balancing # upstream as keyword, springsession as custom name # server as keyword, representing a service or service (a tomcat) # server content as server information in the form of ip: Port # weight defines the weight of server load. Three requests are forwarded to 5688 every four requests and one to 5677upstream springsession {server localhost:5677 weight=1; server localhost:5688 weight=3;}.

Configure when all requests for access to the Nginx are forwarded to both servers for processing

Location / {# root root http://springsession;; # forward to the upstream named springsession for processing proxy_pass http://springsession;}

3) Test load balancer

Visit http://localhost:88/port/get, and Nginx forwards the request to one of the two tomcat for processing. You can find that the result returned by the request is different.

According to the configured weight, 3 out of every 4 visits are handled by 5688 and 1 by 5677. The final average of the weight configuration is only 3 and 1, which may not be handled by 5688 for the first three visits. When weight is not configured, the probability that two tomcat are assigned to each request is 50%.

Once the load balancer is configured, there is a problem:

When you order in window 1, you temporarily store the key in that window, and the next time you order, you may be assigned to window 2 or other window (or window 1), so it is obviously impossible to get the key in other window. Because the other windows don't have your keys. At this point, you can only pray that you will be quickly assigned to window 1.

If the operation of saving the key becomes to save the information in SESSION, then when your request is processed by Tomcat1, Tomcat1 will generate a SESSION for you, you set the information in SESSION, and the next time your request is assigned to Tomcat2 for processing, Tomcat2 will generate a SESSION for you. These are two separate and unshared SESSION. So it is impossible for you to get the information you saved in Tomcat1 in Tomcat2.

The principle of login is to save login status in SESSION. According to the above analysis, login is invalid in cluster deployment services. Log in in Tomcat1, the next time you visit Tomcat2, the login status determined by SESSION must be not logged in, and you need to log in again. The user is crazy, you are crazy, the boss will be crazy.

If there is a common place to store things, and all ordering windows access customer items in the common place, the above problem will be easily solved.

This is the focus of this article: unified management of WEB applications under the cluster SESSION.

Container choice: we need a container that can store SESSION in a unified manner. From the following three points of analysis, Redis is undoubtedly the most appropriate. SESSION is often read, so databases and file systems are not suitable, preferably from memory. SESSION has ID, and an ID corresponds to a SESSION. Preferably, a container of K SESSION V is timed (if not used for a long time, it needs to be deleted). It is best to set the expiration time SESSION access mechanism: since SESSION is generated by Tomcat, the first thing that comes to mind is to modify the SESSION mechanism of Tomcat to access SESSION from Redis, which will bring a problem. If Tocmat is upgraded, we need to modify Tomcat again. Therefore, this scheme is not feasible. We can think of it this way. Even if Tomcat generates SESSION, we still use it in WEB applications. Why not regenerate a SESSION in WEB applications and write such a filter to discard Tomcat's SESSION and get SESSION from Redis before entering the WEB application.

There happens to be such a framework to help us complete the above ideas, only need to configure to achieve unified management of SESSION. This is Spring Session.

To be impressed by the functionality of Spring Session, let's first test how our cluster application handles SESSION without Spring Session

Add a controller method to our load balancing WEB application to output each SESSION ID.

/ * get SESSION ID * / @ RequestMapping ("/ sessionid/get") @ ResponseBodypublic String getPort (HttpServletRequest request, HttpSession session) {int port = request.getLocalPort (); / / port String sessionId = request.getSession (). GetId (); / / SESSION ID return "port:" + port + ", sessionid:" + sessionId;} "

Start the project and visit http://localhost:88/sessionid/get multiple times

The SESSOIN ID under the same Tomcat is unchanged for both visits.

The SESSION ID of two visits under different Tomcat is different.

After visiting a different Tomcat, the SESSION ID also changes when you visit the same Tomcat again.

The reasons for this are as follows:

Visit 5677, because there is no SESSION, Tomcat5677 generates SESSION, ID is 1, and returns 1 to the client to visit 5677. The browser carries SESSION_ID=1 and Tomcat5677 to find the corresponding SESSION. So SESSION_ID is 1 access 5688, browser carries SESSION_ID=1, Tomcat5688 cannot find corresponding SESSION, regenerate SESSION, ID is 2, and return 2 to client access 5677, browser carries SESSION_ID=2, Tomcat5677 cannot find corresponding SESSION, regenerate SESSION, ID is 3, and return 3 to client access 5688, browser carries SESSION_ID=3, Tomcat5688 cannot find corresponding SESSION, regenerate SESSION, ID is 4 And return 4 to the client

4) Unified SESSION management

Let's use Spring Session to manage the SESSION of WEB applications.

1) install Redis and turn it on

See article https://www.jb51.net/article/145704.htm

2) add Spring Session dependencies

/ / Spring Session depends on "org.springframework.session:spring-session-data-redis:2.0.5.RELEASE", / / Redis depends on "io.lettuce:lettuce-core:5.0.4.RELEASE"

3) configure Spring Session filter

Configure the filter provided by Spring Session in Web.xml, which is mainly responsible for replacing the SESSION generated by Tomcat with the SESSION saved in Redis.

SpringSessionRepositoryFilter org.springframework.web.filter.DelegatingFilterProxy springSessionRepositoryFilter / *

4) SpringSession/Redis configuration

Add Spring Session configuration and Redis configuration to the Spring configuration file

Beans {xmlns context: "http://www.springframework.org/schema/context" / / start annotation method context.'annotation-config' () / / configure Spring Session / / actually configure the Spring Session filter used in Web.xml / / replace the Session of Tomcat with the Session sessionConfig (RedisHttpSessionConfiguration) managed in Redis / / configure Redis client connection / / default connection local port 6379 lettuce (LettuceConnectionFactory)}

5) Test

Start the project, visit http://localhost:88/sessionid/get many times, and visit SESSION ID no matter what.

At the same time, the current SESSION record also appears in Redis.

The SESSION process when accessing the WEB application under the cluster after using Spring Session:

Visit 5677, because there is no SESSION in Redis, so a SESSION is generated and stored in Redis. ID is 1, and 1 is returned to the client to visit 5677. The browser carries SESSION_ID=1, and Tomcat5677 finds SESSION in Redis. So SESSION_ID is 1 to access 5688, the browser carries SESSION_ID=1, and Tomcat5688 finds SESSION in Redis. So SESSION_ID clears Redis for 1 and accesses 5677 again. Since there is no SESSION with ID 1 in Redis, it will be regenerated and ID will be changed accordingly.

5) sample code

At this time, we have implemented a unified management SESSION, no matter which TOMCAT we visit, we can find the same SESSION.

When our applications are clustered, unified management of SESSION is imperative. There are many ways to achieve unified management of SESSION, and this paper is only one of them. The most important thing is to make students understand the importance of unified management of SESSION and its basic principles.

Sample code address: https://github.com/atd681/alldemo

Sample project name: atd681-springsession

Summary

The above is the method of SpringSession+Redis cluster session sharing introduced by the editor to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply you in time. Thank you very much for your support to the website!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report