Implementation of Distributed Cookie-session (Spring-session)

Source: Internet
Author: User

Implementation of Distributed Cookie-session (Spring-session)

The spring-session version used in this article is 1.0.0, the address is: https://github.com/spring-projects/spring-session

1 Session Storage Policy

Storage, that is, when using the Setattribute,getattribute of the session in the background, these internally stored data will eventually be stored to where. For example, in the default Tomcat implementation, the corresponding data is stored in memory and is serialized to disk after it is stopped.
You can use memory storage and third-party storage, such as Redis. For clustered session storage, the implementation of third-party storage is sure to be used.

In Spring-session, the session store is defined separately, but the basic guarantee is consistent with the HTTP session, and the main goal is that it can support impersonation in a non-HTTP environment. Therefore, the HTTP session interface is not used directly.
First look at the definition:

12345678 public interface Session {     /** 获取惟一的id,可以理解为即将每个session当作一个实体对象 */    String getId();   <T> T getAttribute(String attributeName);    Set<String> getAttributeNames();    void setAttribute(String attributeName, Object attributeValue);    void removeAttribute(String attributeName);}

From this definition, if you want to use HttpSession, if you implement the session interface, then the implementation can fully implement the httpsession for the storage requirements. For non-httpsession scenes, this can also be used to achieve the purpose of session storage.
Of course, Spring-session also has a expiringsession interface that inherits from the session interface in order to guarantee the use of invalid, last access time, and maximum inactive time in a conversation scenario.

1.0 generation of ID primary key

For the ID, which is understood as the unique key of the session entity object, you can use any one of the unique key generation strategy. For example, use a UUID to generate a unique key. It is also possible to think of this ID as the value Sessioncookie in HTTP

1.1 Map Storage

If it is a map to store, then Set,get,remove can directly use the corresponding implementation of map. Mapsession in the spring-session implementation, that is, an internal hashmap is used for storage.

1.2 Redis Storage

In Sprng-session, the storage of attributes is separated from the storage of the whole, and a specialized warehouse is used to handle the processing of session entities. For the concept of domain model, Set,get,removeattribute is only the processing of attributes, dealing with the change of an internal state, for the whole entity, there is no overall processing. Specifically, in the Redis storage implementation, Spring-session internally uses a mapsession to store the corresponding property information.
After an entity is created, the corresponding property information is all set to Mapsession, and the next property access is handled by Mapsession. To eventually store the corresponding data values, the Redis implementation uses an extra deltamap to hold the changed data and put all the attributes into Redis once again when it is re-saved.
From this implementation, the implementation of Spring-session does not interact with Redis in real time, and this implementation may be problematic when resolving the conflicting properties of the same session setting. Therefore, there is a need to re-implement the corresponding logic in this scenario.

2 Session Warehouse Policy

Separating the storage policy from the warehouse policy is also a design idea for spring-session. Spring designs the session as an entity, thus splitting the operation of the entity object and the operation of the property. The previous storage policy already describes the operation of the property, so the warehouse policy here mainly deals with entity creation, acquisition, update, deletion, and so on, crud. As the following definition shows:

0102030405060708091011121314 public interface SessionRepository<S extends Session> {     /** 新建 */    S createSession();     /** 保存或更新 */    void save(S session);     /** 获取 */    S getSession(String id);      /** 删除 */    void delete(String id);}

2.1 Local Warehouses
In the case of a local repository, you can use a local global globalmap and then use SessionID as the key,mapsession as value.

2.2 Redis Warehouse

In the case of a resi repository, a Redissession object is created locally, and then stored using a hash structure in the Redis store. That is, the structure of <I,<K,V>>. Where I means that sessionid,<k,v> represents a specific Redissession object. The getsession,delete are all for the I operation, and save in the case of specifying I, directly to maintain <K,V>.

In order to be optimized to some extent, and to solve the problem of coverage on certain programs, when Redis is implemented. Spring-session Only stores modified properties, that is, when using setattribute processing properties, Spring-session uses an additional delta to hold the modified attribute, and when the save is last saved, only the part of the data is manipulated. Redis also supports calling Hset to save or update modified data.

3 Session Transfer Policy

3.1 Cookie Transfer

Regular implementations also use cookies to transmit, such as Tomcat,jetty. In this case, when the backend is created, if this is a new session, the native Response.addcookie is automatically called to create a new cookie information. To ensure security, use HttpOnly to create. After each interaction sent to the client, the browser automatically transmits the information to the server side. Then the server side directly from the cookie to get to SessionID, and then further operation.
For this implementation, application development does not require any adjustment, and the browser automatically handles the transfer of the cookie.

3.2 Header Transfer

Header transfer, that is, when creating a new session, use AddHeader to add a new response header to the response header, such as the session header, where the corresponding SessionID value is stored in the Headervalue.
In the client implementation, the client code needs to manually record the response value and add it to the request header when requested. It is also necessary to listen for changes in the response header values, such as the SessionID value change processing. This implementation is a bit more complex to develop than a cookie transmission.

4 HTTP protocol compatible

4.1 To ensure HTTP protocol compatibility, after the session information is ready, it must be processed after the response header

Whether you are using a cookie or a header transmission, you need to ensure that the corresponding header information should be processed first in response to the body output. (A cookie is also a special header). If the following code does not guarantee that the session response is handled correctly

1234 X implementsFilter {     filterChain.doFilter(request,response)     // do session logic}

In this implementation, the do session operation in the filter implementation does not implement the corresponding logic if the output is directly using response's OutputStream in the application code. Because the message mechanism in the HTTP protocol is no longer allowed to output the body after the header information is output.

In the implementation of spring-session, we only need to ensure that the session logic can be processed when the response body is called response processing. You can then use a hack technique that, for the response output, determines whether a specific hack is added to handle our do session when the body is processed or the response should end. Therefore, Oncommittedresponsewrapper is provided for processing at a specific time, and in specific onresponsecommitted, the delete response and save of the session can be processed.

4.2 To support multi-browser access, the corresponding browser parameters should be processed automatically when processing a particular path.

For more browser support, you can look at this article first.
http://docs.spring.io/spring-session/docs/current/reference/html5/#httpsession-multi

In the multi-browser support, the main is to add the corresponding browser identification parameters in the request parameters _s, then in the need for interface jump or other address processing, the background should be able to automatically process the corresponding parameter information. In Spring-session, in order to be transparent to the application, by rewriting the response Encodeurl and Encoderedirecturl, the processing of the corresponding _s is increased to the corresponding processing transparency.

Reprint please indicate source: I Flym
This address: http://www.iflym.com/index.php/code/201503170001.html

Implementation of Distributed Cookie-session (Spring-session)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.