Spring Session from Scratch (1) introduces some basic knowledge of sessions and cookies. This article begins with a formal introduction to how Spring Session transforms traditional sessions. Spring Session: Spring Session provides an API and Implementations for managing a user’s Session information. It also provides transparent integration with:
HttpSession – allows replacing the HttpSession in an application container (i.e. Tomcat) neutral way. Additional features include: Clustered Sessions – Spring Session makes it trivial to support clustered sessions without being tied to an application container specific solution. Multiple Browser Sessions – Spring Session supports managing multiple users’ sessions in a single browser instance (i.e. multiple authenticated accounts similar to Google). RESTful APIs – Spring Session allows providing session ids in headers to work with RESTful APIs WebSocket – provides the ability to keep the HttpSession The features of Spring Session include but are not limited to the following:
Use third-party repositories for clustered session management, often referred to as distributed session containers, instead of application containers (such as Tomcat’s session containers). Spring Session provides three implementations of warehousing (Redis, mongodb, and JDBC), of which Redis is the most common. The implementation of the program, using AOP technology, can be almost transparent replacement. (core) can be very convenient to extend cookies and custom Session related Listener, Filter. Add features like findSessionsByUserName, rememberMe, limit the number of sessions that can be used at the same time for the same account (if set to 1) Let’s start integrating Spring Session step by step
Integrate Spring Sessions using Redis
Introducing dependencies, 1.5.4
org.springframework. Boot
spring-boot-starter-web
< the groupId > org. Springframework. Session < / groupId > < artifactId > spring – the session – data – redis < / artifactId > < / dependency > configuration The Redis Http Session is enabled by the configuration class
@configuration@enablereDisHttpSession Public class HttpSessionConfig {} Is basically 0. The main Configuration scan @enablereDisHttpSession
The application. Yml configuration file configures the redis information for the connection
spring: redis: host: localhost port: 6379 database: 0 write a test Controller to observe Spring Session features, Same code as in the previous article @controller Public class CookieController {@requestMapping (“/test/cookie”) public String cookie(@RequestParam(“browser”) String browser, HttpServletRequest request, SessionBrowser = session.getAttribute(“browser”); If (sessionBrowser == null) {system.out.println (” No session, set browser=” + browser); session.setAttribute(“browser”, browser); } else {system.out.println (” existing session, browser=” + sessionbrowser.toString ()); } Cookie[] cookies = request.getCookies(); if (cookies ! = null && cookies.length > 0) { for (Cookie cookie : cookies) { System.out.println(cookie.getName() + ” : ” + cookie.getValue()); } } return “index”; }} The startup class is omitted, and the test begins.
In the browser to access the following endpoint: http://localhost:8080/test/cookie? Browser = Chrome, here is the result of 4 consecutive visits
1 no session exists, set browser= Chrome 2 There is session, browser= Chrome session: 70791b17-83e1-42db-8894-73fbd2f2a159 3 Existing session, browser= Chrome session: 70791b17-83e1-42db-8894-73fbd2f2a159 4 Existing session, browser= Chrome session: 70791b17-83e1-42DB-8894-73fbd2f2a159 If you remember the running result in the last article, you will find some differences from the original session management. In the original information, we remember that the Key value recorded in the Cookie is JSESSIONID. Instead of RedisHttpSession, it becomes SESSION. Then observe the changes in Redis:
Take a look at the Redis Store and skip it if you don’t get bogged down in details.
- Spring: Session is the default Redis HttpSession prefix (in Redis, we often use ‘:’ as the separator).
- Each session has three related keys. The third key is the most important. It is a HASH data structure that serializes the session information in memory into Redis. SessionAttr: Browser = Chrome, and meta information such as creation time, last access time, etc.
- The other two key, expirations: 1504446540000 and sessions: expires: 7079… I find that most articles do not analyze it, the former is a SET type, and the latter is a STRING type. Some readers may ask, Redis itself has the TTL setting mode of expiration time, why add two extra keys to maintain the session expiration feature? This requires a deep understanding of Redis to come up with this layer of design. Of course, that’s not the point of this section, just to mention: Redis clearing expired keys is an asynchronous behavior and a low-priority behavior that, in the documentation’s own words, may result in sessions not being cleared. ExpiresKey (expiresKey, expiresKey, expiresKey, expiresKey, expiresKey, expiresKey) On the development side, we only need to focus on the third key.
conclusion
This section focuses on how Spring Boot integrates with Spring Sessions, and the next section introduces more complex features. This includes features such as custom Cookie serialization strategies, integration with Spring Security, session lookup by user name, and usage considerations.