Repost: JavaWeb: Redis Storage Session Scheme

Repost address:

http://blog.csdn.net/neosmith/article/details/50466367

All containers that support the Servlet specification come with session management, so most people use HttpSessioninterfaces to store state information. In fact, servlet sessions can make horizontal scaling of application servers very difficult.

Compromise when using Servlet Session

Session Replication

This is undoubtedly a waste of memory, and it can be tolerated for about 5 clusters. If you need dozens or even hundreds of clusters, this is completely unfeasible.

Session Sticky

Although this solution can avoid the above problems, it completely deviates from the original intention of load balancing. If there are servers A and B, A handles requests with sessions 1 to 5, and B handles requests with sessions 6 to 10. If within a certain period of time, users with 1 to 5 sessions have very high access requirements, while 6 to 10 The users of the session do not visit much, which will cause the server A to be overloaded while the server B is very idle. At this time, the load balancing is meaningless.

Session storage with Redis

The interface should be completely deprecated when the application is written, HttpSessionand the state information that needs to be saved is placed in Redis.

generate session id

When the user logs in, the server generates a globally unique string SESSION:日期:20位随机字符串as the key name of the hash data structure in redis, and then returns the identifier to the client as a cookie. After that, the user's subsequent requests will bring this cookie. We write a filter, which is used to read the identifier in the request, retrieve the data corresponding to the identifier from redis, and put it into the HttpServletRequestobject for subsequent use.

session expired

Use the expiration function that comes with redis to set the expiration time for the session id to easily achieve session expiration.

session tracking

We can record the session id of each user, such as saving it in the database, or still put it in redis, so that all session ids of a registered user can be found, and the login function can be easily implemented.

session update

Through AOP, after each request, check whether the session information is updated during the request processing process, and if so, refresh the new data to Redis.

After transferring the session to redis, as long as the operation and maintenance of redis is done, our application server is completely stateless. When expanding horizontally, we only need to add machines without changing any line of code.

Copyright statement: This article is an original article by the blogger, please indicate the source and the original author when reprinting.

Guess you like

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