App backend session information management instance imitating J2EE session mechanism
This article only provides ideas and does not provide specific and complete implementation (bloggers are too lazy to sort out). If you have questions or want to know, you can send private letters or comments
background
In traditional small and medium-sized Java Web projects, session is generally used to temporarily store session information, such as the identity information of the login. This mechanism is implemented by using the cookie mechanism of HTTP. However, it is troublesome for app to save and share cookie information every request, and the traditional session is not friendly to the cluster. Therefore, generally, APP back-end services use tokens to distinguish user login information.
We all know the session mechanism of J2EE very well. It is very convenient to use and is easy to use in traditional Java Web applications. However, there are some problems in Internet projects or projects that can use clusters, such as serialization, synchronization delay and so on. Therefore, we need a tool that can solve the problems of clusters similar to session.
programme
We use the cache mechanism to solve this problem. The popular redis is a NoSQL in memory database with a cache invalidation mechanism, which is very suitable for storing session data. The token string needs to be returned by the server to the client at the first request, and the client will use this token to identify the identity every request in the future. In order to be transparent to business development, we encapsulate the message of APP request and response. We only need to do something about the HTTP request tool class of the client and the MVC framework of the server. The modification of the HTTP tool class of the client is very simple, mainly the protocol encapsulation of the server.
Realization idea
1、 Formulate request response message protocol.
2、 The parsing protocol processes the token string.
3、 Redis is used to store and manage tokens and corresponding session information.
4、 Provides APIs for saving and obtaining session information.
We will explain the implementation scheme of each step step step by step.
1、 Formulate request response message protocol.
Since you want to encapsulate the message protocol, you need to consider what is the public field, what is the business field, the data structure of the message, etc.
The requested public fields generally include token, version, platform, model, IMEI, APP source, etc. token is our protagonist this time.
The public fields of response generally include token, result status (success, fail), result code, result information, etc.
For the message data structure, we choose JSON because JSON is universal, good visualization and low byte occupation.
The request message is as follows. Business information, such as login user name and password, is stored in the body.
Response message
2、 The parsing protocol processes the token string.
We choose the spring MVC framework for the MVC framework on the server side. Spring MVC is also common and will not be described.
Let's not mention the token processing for the moment. First solve how to pass parameters after formulating messages.
Because the request information is encapsulated, in order for the spring MVC framework to correctly inject the parameters we need in the controller, we need to parse and convert the message.
To parse the request information, we need to customize the parameter converter of spring MVC. We can define a parameter converter by implementing the handlermethodargumentresolver interface
Requestbodyresolver implements the resolveargument method and injects parameters. The following code is an example code and should not be used directly.
Configure the self-defined parameter converter into the srpingmvc configuration file < MVC: argument resolvers >
In this way, the parameters in the message can be correctly identified by spring MVC.
Next, we need to process the token. We need to add a srpingmvc interceptor to intercept every request. This is a common function and will not be described in detail
In this way, the token is simply obtained and can be used for public processing.
3、 Redis is used to store and manage tokens and corresponding session information.
In fact, it is to write a redis operation tool class. Because spring is used as the main framework of the project, and we don't use many redis functions, we directly use the CacheManager function provided by spring
Configure org springframework. data. redis. cache. RedisCacheManager
4、 Provides APIs for saving and obtaining session information.
Through the above foreplay, we have handled the token almost. Next, we will implement token management
We need to make business development easy to save and obtain session information, and make the token transparent.
The ThreadLocal variable is used here because a request of the servlet container corresponds to a thread, which is in the same thread in the life cycle of a request, and multiple threads share the token manager, so this thread local variable is required to save the token string.
matters needing attention:
1. The verifytoken method must be called at the beginning of each request. And after the request is finished, call clear to clear it, so that the verifyToken will not be executed if there is an unknown exception next time, but token will be returned from ThreadLocal when it returns. (this bug bothered me for several days, and n development check codes of the company were not found. Finally, after testing, I found that 404 did not enter the interceptor, so I did not call the verifytoken method, resulting in the token in the returned exception information being the last requested token, resulting in a strange serial number problem. Well, remember me a big pot.).
2. The client must save each token when encapsulating the HTTP tool and use it for the next request. The company outsourced its IOS development, but the outsourcing did not comply with the requirements. When it was not logged in, it did not save the token, and the token passed each time was null, resulting in the creation of a token for each request, and the server created a large number of useless tokens.
use
The use method is also very simple. The following is the encapsulated login manager. You can refer to the application of token manager to login manager
The following is a common interface for sending SMS verification code. Some applications also use session to store verification code. I don't recommend this method. There are considerable disadvantages in storing session. Just have a look. I didn't write it
Processing response
Some students will ask, what about the packet encapsulation of the response?
Serviceresponse is the encapsulated response message VO, and we can directly use the @ ResponseBody annotation of springmvc. The key is the builder.
Because it is in the form of a static tool class, the tokenmappool (token manager) object cannot be injected through spring. It is obtained through the API provided by spring. Then, when building the response information, directly call the gettoken () method of tokenmappool, which will return the token string bound by the current thread. Again, be sure to call clear manually after the request is completed (I call it through the global interceptor).
The above example of APP backend session information management that imitates the session mechanism of J2EE is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.