3

I found a mall. I have not logged in. I can add items to the shopping cart. After adding a few items, I am ready to pay. I need to log in first and pay after logging in.

Many shopping malls now require users to log in first, and then add products to the shopping cart after logging in, so that there is a binding relationship between the three objects of user, shopping cart, and product.

For the situation I mentioned at the beginning, it is actually based on session . When the client adds the first product to the shopping cart, it sends a request. After the service receives the request, it creates session , and then returns the current session Corresponding to a JessionId , the browser is stored in cookie . When the client adds the second item to the shopping cart, it carries JessionId . After the server receives the request, it updates session . After the browser is closed, cookie failure, JessionId also lost, need to add items to the shopping cart, by default, session valid for 30 minutes.

In a distributed environment, session will have problems. If the server is deployed on two servers, A and B . When adding a product to the shopping cart for the first time, the request landed on server A. Server A created a session and returned JessionId . When adding a product to the shopping cart for the second time, the request landed on server B, and the request carried JesssionId not find the corresponding server in the B session . At this time, server B will create a new session and return the corresponding JessionId . The client finds that the first added product is missing. . .

Next, session learn how to achieve 060ab0fba349bc consistency in a distributed environment.

One, client storage

Since multiple requests from a client may fall on multiple servers in a distributed environment, can we change the strategy and store the session information directly on the client? Yes, the server stores the session information directly in the cookie, which ensures the consistency of the session, but this is not recommended, because storing some information in the cookie is equivalent to exposing the information to the client , There are serious safety hazards.

Disadvantages :

  • Security problem
  • Cookies have restrictions on data type and data size

Two, session replication

Copy the session of server A to server B, and also copy the session of server B to server A, so that the sessions of the two servers are the same. Like tomcat and other web container supports session replication features in the same LAN , a server session will be broadcast to other servers.

Disadvantages :

There are too many servers in the same network segment, and each server will copy the session, which will cause a waste of server memory.

Three, session stickiness

Use the reverse proxy of the Nginx server to proxy server A and server B, and then use ip_hash to bind the client and server. That is to say, the first time client A visits server B, then the first The second visit must also be server B, so there is no session inconsistency.

Disadvantages :

If server A goes down, the sessions of client A and client B will be lost.

Fourth, session centralized management

This is the way all servers session unified management, you can use redis other high-performance servers to centrally manage session, and spring to official spirng-session is one such deal session consistency problems. session solution that is currently used in enterprise development.

Five, spring-session actual combat

Spring provides a solution for dealing with distributed sessions- Spring Session . Spring Session provides APIs and implementations for managing user sessions.

Spring Session provides support for commonly used repositories such as redis , mongodb , mysql Spring Session provides HttpSession , which means that developers can use the implementation of Spring Session support to switch HttpSession . It's the original formula, and it has a different taste!

Spring Session adds a SessionRepositoryFilter filter to modify the package request and response. The packaged request is SessionRepositoryRequestWrapper . When the getSession() method is called, the session implemented by Spring Session

Spring Session is very simple to use. After adding related dependencies, directly operate HttpSession to achieve the effect.

first step : add Spring Session and redis related dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

Second step : Configure redis related information

spring:
  redis:
    # redis库
    database: 0
    # redis 服务器地址
    host: localhost
    # redis 端口号
    port: 6379
    # redis 密码
    password:
  # session 使用redis存储  
  session:
    store-type: redis

third step : use session in the project

public String sessionTest(HttpServletRequest request){

    HttpSession session = request.getSession();
    session.setAttribute("key","value");
    return session.getAttribute("key").toString();
}

redis stores three pieces of information.

  • The first to store the id of this Session is a Redis data structure of Set type. The last value of 1439245080000 in this k is a timestamp, which is calculated by scrolling to the next minute according to the expiration time of this Session.
  • The second is used to store the detailed information of the Session, including the expiration interval of the Session, the most recent access time, attributes, and so on. The expiration time of this k is the maximum expiration time of the Session + 5 minutes. If the default maximum expiration time is 30 minutes, the expiration time of this k is 35 minutes.
  • The third is used to indicate the expiration of the Session in Redis. This kv does not store any useful data, but is set to indicate that the Session expires. The expiration time of this k in Redis is the expiration time interval of the Session.

Why store three pieces of data in a session instead of one! For the realization of the session, you need to monitor its creation, expiration and other events. Redis can monitor the changes of a certain key, and when the key changes, it can quickly make corresponding processing.

But there are two ways to have expired keys in Redis:

  • It was found to expire when visited
  • Redis background gradually finds expired keys

When it is found to be expired during access, an expired event will be generated, but there is no guarantee that an expired event will be generated immediately after the expiration time of the key arrives.

In order to generate the expiration event when the Session expires in time, spring-session adds:

spring:session:sessions:expires:726de8fc-c045-481a-986d-f7c4c5851a67
spring:session:expirations:1620393360000

There is a timed task in spring-session, every minute it will query the corresponding spring:session:expirations: of the whole minute, and then visit this SessionId again, that is, spring:session:sessions: expires:SessionId , so that Redis can generate key expiration events in a timely manner—that is, Session expiration events.

reference

https://www.cnblogs.com/sxw123/p/13803478.html

Pay attention, don't get lost

If you think the article is good, welcome to pay attention, like, and collect. Your support is the driving force for my creation. Thank you all.

If there is a problem with the writing of the article, please don't hesitate to write, welcome to leave a message and point out, I will check and modify it in time.

If you want to see more things, you can search for "Java Journey" on WeChat to follow. Reply to the "Manual" to receive the Java Interview Manual!


Java旅途
1.1k 声望6.1k 粉丝