Spring boot also encapsulates the NoSQL database by automating the usual database support.
About Redis
Redis is the most widely used memory data store in the industry today. Supports a richer data structure than memcached,redis, such as hashes, lists, sets, etc., while supporting data persistence. In addition to this, Redis also provides some features of the class database, such as transactions, HA, and master-slave libraries. It can be said that Redis has a number of features of the cache system and database, so it has a rich application scenario. This article describes the two typical applications of Redis in spring boot.
How to use
1. Introduction of Spring-boot-starter-redis
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>
2. Adding configuration Files
# REDIS (redisproperties)# Redis Database index (default = 0) Spring. Redis. database=0# Redis Server address Spring. Redis. host=192.168.0.58# Redis Server Connection Port Spring. Redis. port=6379# Redis Server connection password (default is empty) spring. Redis. password=# Connection Pool Maximum number of connections (use negative values to indicate no limit) spring. Redis. Pool.max-active=8 # Connection pool Maximum blocking wait time (using negative values to indicate no limit) Spring.redis.pool.max-wait=-1 # Maximum idle connection in connection pool Spring.redis.pool.max-idle=8 # the minimum idle connection in the connection pool spring< Span class= "Hljs-preprocessor" >.redis.pool0 # Connection time-out (ms) spring .redis.timeout=0
3, OK, then you can directly use the
@RunWith (Springjunit4classrunner.class)@SpringApplicationConfiguration (Application.class)PublicClassTestredis {@AutowiredPrivate Stringredistemplate stringredistemplate;@AutowiredPrivate Redistemplate redistemplate;@TestPublicvoidTest ()Throws Exception {Stringredistemplate.opsforvalue (). Set ("AAA","111"); Assert.assertequals ("111", Stringredistemplate.opsforvalue (). Get ("AAA")); }@TestPublicvoidTestobj ()Throws Exception {User user=New User ("[Email protected]","AA","aa123456", "AA","123"); Valueoperations<string, user> operations=redistemplate.opsforvalue (); Operations.set ("com.neox", user), Operations.set ("COM.NEO.F", user,1,timeunit.seconds); Thread.Sleep (1000); //redistemplate.delete ("com.neo.f"); boolean Exists=redistemplate.haskey ("com.neo.f"); if (exists) {System.out.println ("exists is true");} else{System.out.println ("exists is false");} //Assert.assertequals ("AA", Operations.get ("Com.neo.f"). GetUserName ());}}
These are the manual use of the way, how to find the database automatically use the cache, see below;
4. Automatically generate cache based on method
@RequestMapping("/getUser")@Cacheable(value="user-key")public User getUser() { User user=userRepository.findByUserName("aa"); System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功"); return user;}
Where value is the key that is cached in Redis
Share Session-spring-session-data-redis
In distributed systems, Sessiong sharing has a number of solutions, where hosting into the cache should be one of the most common scenarios,
Spring Session Official Description
Spring session provides an APIs and implementations for managing a user ' s session information.
How to use
1. Introduction of dependency
<dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId></dependency>
2. Session Configuration:
@Configuration@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30)public class SessionConfig {}
Maxinactiveintervalinseconds: Set session Expiration time, after using Redis session, the Server.session.timeout property of the original boot is no longer valid
Okay, so it's configured, let's test it.
3. Testing
Add test method Get SessionID
@RequestMapping("/uid") String uid(HttpSession session) { UUID uid = (UUID) session.getAttribute("uid"); if (uid == null) { uid = UUID.randomUUID(); } session.setAttribute("uid", uid); return session.getId(); }
Sign in to Redis inputkeys ‘*sessions*‘
t<spring:session:sessions:db031986-8ecc-48d6-b471-b137a3ed6bc4t(spring:session:expirations:1472976480000
1472976480000 of which is the time of failure, meaning that the session expires after this time, db031986-8ecc-48d6-b471-b137a3ed6bc4
for SessionID, login Http://localhost:8080/uid found will be consistent, indicating session has been effectively managed in Redis.
How to share a session in two or more Taichung
In fact, according to the above steps in another project is configured again, automatically after the start of the session to share.
Example code address reference
Two typical application scenarios for Redis
Distributed sessions for Pringboot applications
a pure Smile
Source: www.ityouknow.com
All rights reserved, welcome to keep the original link to reprint:)
Use of Redis in Spring boot