Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to treat session and redis in pringboot Cluster

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to treat session and redis about pringboot cluster. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

When talking about the cluster solution, the first problem we will encounter is the session problem. On a single machine, the problem of session is always solved by the web container. We mainly use it, but clustering means multiple containers. If the load balancer randomly allocates server access, it is easy to go to server B for the next access after server A logs in. As a result, server B does not have the user's session in the web container, and the result will be tragic. So what to do, of course, redis to deal with, redis centralized storage of session, no matter which server accesses session is redis, the local server does not save session, this problem is solved perfectly. This solution falls on the concrete implementation, and the first thing that comes to mind is spring's own solution, spring session.

1. Spring session+redis runs

Spring session+redis 's solution is very simple. Please follow the steps:

Step 1:pom file plus starter

Org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-web org.springframework.session spring-session-data-redis

Spring-boot-starter-web introduces web dependency, spring-boot-starter-data-redis is the access of redis, and spring-session-data-redis takes redis as the storage location of session and does related operations.

Step 2: write the configuration of redis into application.properties

# REDIS# Redis database index (default is 0) spring.redis.database=0 # Redis server address spring.redis.host=myip# Redis server connection port spring.redis.port=6379 # Redis server connection password (default is empty) maximum number of spring.redis.password=password# connection pool connections (use negative values for no limit) default 8spring.redis.lettuce.pool.max-active=8# connection pool maximum blocking wait time (use Negative value means no limit) default-maximum idle connection in 1spring.redis.lettuce.pool.max-wait=-1# connection pool default 8spring.redis.lettuce.pool.max-idle=8# connection pool minimum idle connection default 0spring.redis.lettuce.pool.min-idle=0

Step 3: add the relevant comments to the startup class

@ SpringBootApplication@EnableCaching@EnableRedisHttpSession (maxInactiveIntervalInSeconds = 86400 / 30) public class RedisApplication {public static void main (String [] args) {SpringApplication.run (RedisApplication.class, args);}}

@ EnableCaching means to enable caching. Because we have configured redis in the application.proerties file, the default redis is used as the project cache; @ EnableRedisHttpSession means that redis stores httpsession, and then session is automatically stored in redis.

Let's open a controller and see if it is like this:

@ RestControllerpublic class IndexController {@ RequestMapping ("/ saveSession") String saveSession (HttpSession session) {session.setAttribute ("mySession", "lalala"); return session.getId ();} @ RequestMapping ("/ getSession") String getSession (HttpSession session) {String mySessionString = session.getAttribute ("mySession") .toString (); return mySessionString;}

The methods of saveSession and getSession are very simple, one is to store session and the other is to fetch session

Let's use redis-cli to see if the session is saved to redis:

As you can see, session is automatically stored in redis. It can be seen that the implementation of session to redis, and then sharing, is very simple.

The source code of this piece can be seen here.

2. The storage structure of session in redis

When you look at the session with redis-cli above, you can see that the session is indeed stored, but the way it is stored is not so clear, it can be said.

2.1, namespace and other properties

First of all, the stored key value, such as the one in the screenshot above, is as follows:

Spring:session:sessions:54abb3f7-909a-46c8-ab4c-1b515eff69b1

Spring:session is the namespace of spring session in redis. The default is "spring:session", which can be seen in the source code of org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration:

This namespace can be changed. In the source code of @ EnableRedisHttpSession, we can see that there are several parameters that can be passed into the configuration.

Public @ interface EnableRedisHttpSession {/ * The session timeout in seconds. By default, it is set to 1800 seconds (30 minutes). * This should be a non-negative integer. * @ return the seconds a session can be inactive before expiring * / int maxInactiveIntervalInSeconds () default MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS; / * * Defines a unique namespace for keys. The value is used to isolate sessions by * changing the prefix from default {@ code spring:session:} to * {@ code:} *

* For example, if you had an application named "Application A" that needed to keep * the sessions isolated from "Application B" you could set two different values for * the applications and they could function within the same Redis instance. * @ return the unique namespace for keys * / String redisNamespace () default RedisOperationsSessionRepository.DEFAULT_NAMESPACE; / * * Flush mode for the Redis sessions. The default is {@ code ON_SAVE} which only * updates the backing Redis when {@ link SessionRepository#save (Session)} is invoked. * In a web environment this happens just before the HTTP response is committed. *

* Setting the value to {@ code IMMEDIATE} will ensure that the any updates to the * Session are immediately written to the Redis instance. * @ return the {@ link RedisFlushMode} to use * @ since 1.1 * / RedisFlushMode redisFlushMode () default RedisFlushMode.ON_SAVE; / * The cron expression for expired session cleanup job. By default runs every minute. * @ return the session cleanup cron expression * @ since 2.0.0 * / String cleanupCron () default RedisHttpSessionConfiguration.DEFAULT_CLEANUP_CRON;}

MaxInactiveIntervalInSeconds is the expiration time of the data in session (not the expiration time of session in redis)

RedisNamespace is the namespace of session in spring session and key in redis.

RedisFlushMode is the way redis saves session, and the default is ON_SAVE. There are two ways: IMMEDIATE: save as soon as you create the session; ON_SAVE: it is not saved when you create the session, but when you add data to the session

CleanupCron session expires when the data cleaning scheduled task, the default configuration is once a minute, why to configure this, we will talk about later.

Let's configure a namespace in @ EnableRedisHttpSession to see the effect.

@ EnableRedisHttpSession (maxInactiveIntervalInSeconds = 86400,030redisNamespace = "wphmoon:session") public class RedisApplication {.}

Visit the saveSession method above to take a look at the data structure of session in redis:

2.2 Storage structure of session in redis

As you can see in the image above, the namespace has been modified. Let's take a look at what the value behind key looks like.

Failed, because session to redis is not saved as a string, it is stored in a format of

Using hash, let's take a look at it with hget.

Can not be found, the reason is that mySession is not a complete field name, complete is like this

If you look at the familiar lalala, you will know that we have finally found it this time. The complete fieldName should be preceded by sessionAttr in front of the Attribute we named. But what is the "\ xac\ xed\ x00\ x05t\ x00\ x06" in front of lalala?

This depends on going through the source code, so I started to look inside spring-session-data-redis-XXX.jar and saw the class SpringSessionRedisOperations. The name looks like an operation class that pushes session to redis (it itself is a comment, and the author in the code is very sweet to tell us which implementation to look at).

In the RedisOperationsSessionRepository class, I accidentally found this.

Originally sessionAttr: it was defined here, and I also found this.

The original namespace to add sessions is here, but the main reason for us to turn over the code this time, to see the random strings in the value content is not here, in another class ReactiveRedisOperationsSessionRepository. It actually operates on the session store by calling another interface class:

In the end, there are only two implementation classes for this interface, which are inheritance relationships.

When I see RedisTemplate, I finally see my old friend, the tool we use most often when using redis. Take a look at how it operates hash.

You can tell from the name of the parameter that this must have been serialization-processed, so you can see this sentence in RedisSerializationContext.

It seems that when all session is stored in redis, it needs to be serialized, and the pile in front of the real string is the serialized tag content.

On the pringboot cluster how to view session and redis to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report