1. Cookie, localStorage, sesstionStrorage as common methods of communication between the client and the server, there are many similarities and differences, applicable to different scenarios, so the following sorting is made:
- 1.cookie
Cookies can authenticate users at the front and back ends and mark users.
It is generally generated by the server, and the expiration time can be set. It is carried in the HTTP header each time. If the cookie stores too much data, it will affect the performance, so it is generally used to identify the user (the size of data stored is 4KB).
- 2.Localstorage
LocalStorage is a new addition to the HTML5 standard technology, of course, as early as the IE6 era there is a userData thing for localStorage, and at that time considering the compatibility of the browser, the more general scheme is to use flash. LocalStorage is now supported by most browsers. It is only saved in the client (browser) and does not participate in the communication of the server. The cached data in the user’s browser will not be deleted if the user actively clears the cache in the browser (the stored data is about 5MB).
- 3.sessionStorage
SessionStorage and localStorage interface is similar, but the life cycle of data storage is different from that of localStorage, it can only save part of the data in the current session, close the page or browser will be cleared (storage data about 5MB)
Development: the session
Session is marked by cookie. When the user needs to remember the user, usually during login, the server will Set a response header set-cookie and send it back to the client. After receiving the response, the client will send each subsequent request with this cookie. The session is stored on the server, and the cookie value in each request sent by the client is compared with the session of the server, so that the client information can normally access the interface request.
Real cases: In the case of multi-service server cluster (such as Taobao), different servers will be assigned to different business requirements, but under the same domain name, so the session will occupy a large amount of space and memory. The server not only needs to process services, but also needs to maintain the synchronization of sessions. In this way, The server cannot be expanded by adding services and cannot be scaled horizontally.
- The solution
(1) Shared session
Extract sessions and store them centrally in a common memory space
(2) token
The server does not need to store the token. The server can determine whether the token is in the login state by parsing the information in the token. The token can carry the information parsed by the cookie in the token, which effectively alleviates the storage burden on the server