Spring provides a solution for handling distributed sessions: Spring-Session. Spring-Session provides support for common storage such as Redis, MongoDB, MySQL, etc. Spring-Session provides transparent integration with HttpSession, which means developers can use the implementation supported by Spring-Session to switch HttpSession to Spring-Session.
Step 1. Add dependencies
Add the dependencies of Redis and Spring-Session to the pom.xml file of the project Bag.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>
Step 2. Configure Redis and Spring-Session persistence methods
The author is accustomed to using application.properties as the SpringBoot configuration file, or you can use application.yml to configuration. Add the following configuration in the application.properties configuration file.
# 配置 Redis 服务器地址(此处是一个虚假地址) spring.redis.host=10.211.12.6 # 配置 Redis 端口 spring.redis.port=6379 # 配置 Redis 密码 spring.redis.password=123456 # 其他 Redis 的配置还有很多,例如 Redis 连接池的配置,此处暂时只配置上述几项关键点 # spring session 配置 spring.session.store-type=redis
Step 3. Use JSON serialization mechanism
Spring-Session uses the JDK serialization mechanism by default, which requires the class to implement the Serializable interface, and the serialization is binary bytes Arrays are difficult to understand. Using the JSON serialization mechanism, the serialized string is easy to understand.
package com.test.conf; import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.serializer.RedisSerializer; // spring session 使用 json 序列化机制 @Configuration public class SessionConfig { @Bean public RedisSerializer<Object> springSessionDefaultRedisSerializer() { return new GenericFastJsonRedisSerializer(); } }
#Step 4. Add the @EnableRedisHttpSession annotation to the SpringBoot startup class to open Spring-Session
package com.test; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; @SpringBootApplication // 开启 Spring-Session @EnableRedisHttpSession // @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800, redisNamespace = "test:session") public class TestSessionAppApplication { public static void main(String[] args) { SpringApplication.run(TestSessionAppApplication.class, args); } }
Add the @EnableRedisHttpSession annotation to open Spring-Session. The annotation has several parameters that can be set individually, among which maxInactiveIntervalInSeconds represents the Session expiration time, the default value is 30 minutes; redisNamespace represents the namespace when the Session is stored in Redis, that is, the key name prefix of the Session stored in Redis, the default value is "spring :session", in actual projects, different systems may use the same Redis in order to save resources. In order to distinguish the Sessions of different systems, a separate namespace can be set for each system.
2.1 Controller layer writing test demo
@RequestMapping(value = "testSession") public String testSession(HttpServletRequest request) { HttpSession session = request.getSession(); log.info("sessionId:[{}]", session.getId()); session.setAttribute("name", "Lucy"); session.setAttribute("age", "20"); return session.getAttribute("name").toString(); }
2.2 Test process
At the same time, start the SpringBoot project with different ports 9001/9002. Simulate different nodes in a distributed cluster on your local computer. Use Google Chrome to open the link http://localhost:9001/testSession. The server prints the log as shown below.
sessionId:[5c417104-4f6d-430d-b569-cbc1e19cdf02]
The client logs in to the Redis server and views the Session content in Redis.
[testuser@vm ~]$ redis-cli -h 10.211.12.6 -p 6379 10.211.12.6:6379> auth 123456 OK 10.211.12.6:6379> keys * 1) "spring:session:expirations:1658127780000" 2) "spring:session:sessions:5c417104-4f6d-430d-b569-cbc1e19cdf02" 3) "spring:session:sessions:expires:5c417104-4f6d-430d-b569-cbc1e19cdf02"
Redis will store three key-value pairs (hereinafter referred to as key-value) for each RedisSession:
The first key-value stores the Id of this Session. , is a Redis data structure of Set type. The last 1658127780000 value in this key is a timestamp calculated based on the Session expiration moment rolled to the next minute.
The second key-value is used to store the detailed information of the Session. It is a Hash type Redis data structure, including the latest access time of the Session (lastAccessedTime) and the expiration interval (maxInactiveInterval). , the default is 30 minutes, the seconds value saved here), creation time (creationTime), sessionAttr, etc.
The third key-value is used to represent the expiration time of the Session in Redis. It is a Redis data structure of String type. This key-value does not store any useful data, it is just set to indicate Session expiration. The expiration time of this key in Redis is the expiration interval of the Session. You can use the ttl command to view the expiration time of the key, which is the expiration time of the Session.
During this test, the data details in Redis are as follows.
10.211.12.6:6379> type spring:session:expirations:1658127780000 set 10.211.12.6:6379> smembers spring:session:expirations:1658127780000 1) "\"expires:5c417104-4f6d-430d-b569-cbc1e19cdf02\"" 10.211.12.6:6379> 10.211.12.6:6379> type spring:session:sessions:5c417104-4f6d-430d-b569-cbc1e19cdf02 hash 10.211.12.6:6379> hgetall spring:session:sessions:5c417104-4f6d-430d-b569-cbc1e19cdf02 1) "lastAccessedTime" 2) "1658125969794" 3) "maxInactiveInterval" 4) "1800" 5) "creationTime" 6) "1658125925139" 7) "sessionAttr:age" 8) "\"20\"" 9) "sessionAttr:name" 10) "\"Lucy\"" 10.211.12.6:6379> 10.211.12.6:6379> type spring:session:sessions:expires:5c417104-4f6d-430d-b569-cbc1e19cdf02 string 10.211.12.6:6379> get spring:session:sessions:expires:5c417104-4f6d-430d-b569-cbc1e19cdf02 "" 10.201.42.26:6379>
Check the browser cookie. At this time, the browser already has a cookie in use, as shown in the figure below.
Refresh the browser, the SessionId printed by the backend remains unchanged, the Session content in Redis is not added, and the browser returns the content normally. It means that the session operation of this node is normal.
With the same browser, open another test port link http://localhost:9002/testSession. The browser automatically carries cookies. The backend print content is the same and the Redis content is the same (the expiration time has been updated), indicating that the cluster Sessions are shared between nodes.
Although Spring-Session provides an easy-to-use, nearly transparent integration method that makes supporting cluster sessions trivial, in fact Spring- Session has some flaws.
It is impossible to publish Session expiration and destruction events in real time;
The serialization method may not be supported for some specific types of sessions. Not very good;
Redis requires 3 key values to store a session, which takes up slightly more space;
In high concurrency scenarios, Because Session is not a CAS (Compare And Set) operation, there may be some concurrency issues (minor issues).
Although Spring-Session has some shortcomings, overall it is still very usable. In addition, you can write a set of filters yourself to optimize the shortcomings of Spring-Session and implement distributed sessions.
The above is the detailed content of How SpringBoot integrates Spring Session to implement distributed sessions. For more information, please follow other related articles on the PHP Chinese website!