How to use Spring boot to quickly build a distributed session cache based on Redis
Use Spring boot to quickly build a distributed session cache solution based on Redis
In large-scale web applications, session management is very important, which cannot be satisfied by single-machine storage.
Usually the following are One method:
Persist the session into the database. But the disadvantage is that the cost of reading and writing is too high.
De-session, such as Information is stored in cookies. But the disadvantage is that the size is limited and it is not safe.
3. Store the session in a distributed nosql database, such as Redis.
Step one: Build the Spring Boot development environment
Add the maven core dependency spring-session-data-redis
<!--基于redis的分布式session存储--> <dependency> <groupid>org.springframework.session</groupid> <artifactid>spring-session-data-redis</artifactid> </dependency>
Configure the redis connection properties in the application.properties file
###### Redis config start ###### spring.redis.database=0 spring.redis.host=192.168.41.60 spring.redis.port=6379 spring.redis.password= spring.redis.pool.max-active=20 spring.redis.pool.max-wait=-1 spring.redis.pool.max-idle=8 spring.redis.pool.min-idle=0 spring.redis.timeout=0 ###### Redis config end ######
Step 2: Open the @EnableRedisHttpSession annotation
@Configuration @EnableRedisHttpSession(redisNamespace = "mysession",maxInactiveIntervalInSeconds = 60*60*24) public class SessionConfig
The source code of the @EnableRedisHttpSession annotation is as follows. You can see that three parameters can be configured:
maxInactiveIntervalInSeconds: The expiration time of the data in the session (not the expiration time of the session in redis)
In my configuration, I specified a namespace named "mysession" , used to identify the current application
redisFlushMode: the way redis saves the session, the default ON_SAVE
has two ways: IMMEDIATE: Once the session is created Just save it immediately.ON_SAVE: It will not be saved when creating the session, but it will be saved when adding data to the session
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({ java.lang.annotation.ElementType.TYPE }) @Documented @Import(RedisHttpSessionConfiguration.class) @Configuration public @interface EnableRedisHttpSession int maxInactiveIntervalInSeconds() default 1800; String redisNamespace() default ""; RedisFlushMode redisFlushMode() default
Step 3: Test
Write a controller
@RestController public class HelloController @RequestMapping("/hello/{username}") public String hello(HttpSession session, @PathVariable(value = "username") String username) { session.setAttribute("username", username); return "保存session到Redis成功"; } @RequestMapping("/getName") public String getUsername(HttpSession session) { String username = (String) session.getAttribute("username"); return
When the browser accesses the link http://localhost:8080/hello/admin, the
hello method will receive the link passed by the browser Parameters and save them in the session, and then save the session to Redis
By viewing the information in redis, you can see the following information:
The spring:session is automatically added, we The created namespace mysession is under this default directory
Next we visit http://localhost:8080/getName, and you can see that the browser will display the admin## we saved in the session just now. #
The above is the detailed content of How to use Spring boot to quickly build a distributed session cache based on Redis. For more information, please follow other related articles on the PHP Chinese website!

Redisoutperformstraditionaldatabasesinspeedforread/writeoperationsduetoitsin-memorynature,whiletraditionaldatabasesexcelincomplexqueriesanddataintegrity.1)Redisisidealforreal-timeanalyticsandcaching,offeringphenomenalperformance.2)Traditionaldatabase

UseRedisinsteadofatraditionaldatabasewhenyourapplicationrequiresspeedandreal-timedataprocessing,suchasforcaching,sessionmanagement,orreal-timeanalytics.Redisexcelsin:1)Caching,reducingloadonprimarydatabases;2)Sessionmanagement,simplifyingdatahandling

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download
The most popular open source editor

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