introduction
Session management is a key challenge in distributed application architecture. Traditional methods of storing sessions in containers are difficult to share among multiple service instances, resulting in lost sessions when users switch between different servers.
Spring Session provides a standard way to create and manage user sessions, allowing sessions to be separated from the limitations of application servers and enable session sharing across multiple service instances.
1. Basic concepts of Spring Session
Spring Session is a project in the Spring ecosystem that provides a suite of APIs and implementations to manage user sessions. Its core advantage is that it can strip session storage from the application server and place it into an external storage system, thereby realizing cross-application sharing and persistence of sessions.
The main features of Spring Session include:
- Transparent integration: almost non-invasive to existing application code
- Multiple storage methods: Supports Redis, JDBC, MongoDB and other backend storage
- Security Support: Seamless integration with Spring Security
- REST API support: provides a request header-based session delivery mechanism, suitable for RESTful applications
- WebSocket support: Ensure the continuity of sessions in WebSocket communication
To use Spring Session in your project, you need to add the corresponding dependencies first. Taking the Spring Boot project as an example, select the corresponding dependency according to the storage type:
<!-- Redisstorage --> <dependency> <groupId></groupId> <artifactId>spring-session-data-redis</artifactId> </dependency> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- orJDBCstorage --> <dependency> <groupId></groupId> <artifactId>spring-session-jdbc</artifactId> </dependency> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
2. Redis implements session storage
Redis is a high-performance key-value storage system that is ideal for storing session data.
With low latency, high availability and horizontal scaling capabilities with Redis storage sessions, it is ideal for session management in distributed systems.
2.1 Configuring Redis Session Storage
In Spring Boot applications, configuring Redis session storage is very simple:
import ; import ; import ; import ; import ; @Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800) // Session expiration time: 30 minutespublic class RedisSessionConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); (connectionFactory); return template; } }
@EnableRedisHttpSession
Annotation is automatically configuredRedisIndexedSessionRepository
, it is responsible for the creation, saving, deletion and expiration of sessions.
Configure Redis connection information in or:
# Redis Server Connection Configuration=localhost =6379 # If password authentication is required=your-password # Spring Session Configuration-type=redis =spring:session
2.2 Redis Session Example
The working mechanism of Redis session storage is transparent, and developers can use it like using normal HttpSession:
import ; import ; import ; @RestController public class SessionController { @GetMapping("/session/set") public String setSessionAttribute(HttpSession session) { ("username", ""); ("role", "admin"); return "Session attributes set successfully"; } @GetMapping("/session/get") public String getSessionAttribute(HttpSession session) { String username = (String) ("username"); String role = (String) ("role"); return "Username: " + username + ", Role: " + role; } }
In the background, Spring Session intercepts the operation of HttpSession and stores the session data in Redis. The data structure of Redis storage session is as follows:
-
spring:session:sessions:<sessionId>
- Storage session itself -
spring:session:sessions:expires:<sessionId>
- Store expiration information for sessions -
spring:session:expirations:<expireTime>
- List of sessions indexed by expiration time
3. JDBC implements session storage
For applications that already use relational databases, JDBC session storage is a good choice. It leverages existing database infrastructure to simplify system architecture and operational complexity.
3.1 Configuring JDBC session storage
In Spring Boot applications, configuring JDBC session storage is equally simple:
import ; import ; @Configuration @EnableJdbcHttpSession(maxInactiveIntervalInSeconds = 1800, tableName = "SPRING_SESSION") public class JdbcSessionConfig { // JDBC session storage does not require additional bean definitions}
@EnableJdbcHttpSession
Annotation configuredJdbcIndexedSessionRepository
, It uses JDBC to store and retrieve session data.
Configure the data source and session storage types in:
# Data source configuration=jdbc:mysql://localhost:3306/session_db =root =password -class-name= # Spring Session Configuration-type=jdbc -schema=always
Spring Session will automatically create the required database tables. By default, the following table is created:
-
SPRING_SESSION
-Storing session metadata -
SPRING_SESSION_ATTRIBUTES
- Store session properties
3.2 JDBC session table structure
The table structure used by JDBC session storage is as follows:
CREATE TABLE SPRING_SESSION ( PRIMARY_ID CHAR(36) NOT NULL, SESSION_ID CHAR(36) NOT NULL, CREATION_TIME BIGINT NOT NULL, LAST_ACCESS_TIME BIGINT NOT NULL, MAX_INACTIVE_INTERVAL INT NOT NULL, EXPIRY_TIME BIGINT NOT NULL, PRINCIPAL_NAME VARCHAR(100), CONSTRAINT SPRING_SESSION_PK PRIMARY KEY (PRIMARY_ID) ); CREATE TABLE SPRING_SESSION_ATTRIBUTES ( SESSION_PRIMARY_ID CHAR(36) NOT NULL, ATTRIBUTE_NAME VARCHAR(200) NOT NULL, ATTRIBUTE_BYTES BLOB NOT NULL, CONSTRAINT SPRING_SESSION_ATTRIBUTES_PK PRIMARY KEY (SESSION_PRIMARY_ID, ATTRIBUTE_NAME), CONSTRAINT SPRING_SESSION_ATTRIBUTES_FK FOREIGN KEY (SESSION_PRIMARY_ID) REFERENCES SPRING_SESSION(PRIMARY_ID) ON DELETE CASCADE );
These tables store session ID, creation time, last access time, expiration time, and all session properties.
4. Advanced features and best practices
4.1 Custom session serialization
By default, Spring Session uses JDK serialization to store session properties. To improve performance and compatibility, the serialization mechanism can be customized:
import ; import ; import .GenericJackson2JsonRedisSerializer; import ; import ; @Configuration @EnableRedisHttpSession public class RedisSessionConfig { @Bean public RedisSerializer<Object> springSessionDefaultRedisSerializer() { return new GenericJackson2JsonRedisSerializer(); } }
For JDBC storage, it can be implementedSessionConverter
Customize interface serialization:
@Configuration @EnableJdbcHttpSession public class JdbcSessionConfig { @Bean public SessionConverter sessionConverter() { return new JacksonSessionConverter(); } }
4.2 Session event listening
Spring Session provides a series of events that allow developers to execute custom logic at different stages of the session life cycle:
import ; import .*; import ; @Component public class SessionEventListener { @EventListener public void onCreation(SessionCreatedEvent event) { ("Session created: " + ()); } @EventListener public void onExpiration(SessionExpiredEvent event) { ("Session expired: " + ()); } @EventListener public void onDeletion(SessionDeletedEvent event) { ("Session deleted: " + ()); } }
4.3 Multi-browser session support
Spring Session supports maintaining independent sessions on different browsers or devices of the same user:
import ; import ; import ; @Configuration public class SessionConfig { @Bean public CookieSerializer cookieSerializer() { DefaultCookieSerializer serializer = new DefaultCookieSerializer(); ("SESSION"); ("/"); ("^.+?\\.(\\w+\\.[a-z]+)$"); return serializer; } }
V. Performance and safety considerations
When using Spring Session in a production environment, the following performance and safety factors need to be considered:
- Redis persistence: Configure Redis's persistence policy (AOF or RDB) to ensure that session data is not lost when Redis service restarts.
- Connection pool management: Configure appropriate connection pools for Redis or databases to avoid exhaustion of connection resources.
- Session Cleanup: Regularly clean out expired session data, especially when using JDBC storage.
- Session timeout: Set a reasonable session timeout according to application security requirements.
- Cookie security: Configure the security properties of session cookies:
@Bean public CookieSerializer cookieSerializer() { DefaultCookieSerializer serializer = new DefaultCookieSerializer(); (true); // Transfer only in HTTPS connection (true); // Prevent JavaScript access ("Strict"); // Prevent CSRF attacks return serializer; }
Summarize
Spring Session provides a powerful and flexible session management solution for distributed applications. By transferring session data from application servers to external storage such as Redis or relational databases, cross-service instance sharing of sessions is realized, laying the foundation for building a scalable distributed system.
The Redis storage solution provides high performance and high availability, suitable for applications with high response time requirements; while the JDBC storage solution makes full use of existing database infrastructure and is suitable for projects that have already used a large number of relational databases.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.