How SpringBoot integrates Spring Session to implement distributed sessions
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.
1. Configuration and development
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. Test
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.
3. Disadvantages of Spring-Session
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

This article will write a detailed example to talk about the actual development of dubbo+nacos+Spring Boot. This article will not cover too much theoretical knowledge, but will write the simplest example to illustrate how dubbo can be integrated with nacos to quickly build a development environment.
