Software 152 Hi-ray Shunda redis Introduction
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 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 # the maximum idle connection in the connection pool Spring.redis.pool.max-idle=8 # the minimum idle connection in the connection pool Spring.redis.pool.min-idle=0 # Connection time-out (ms) Spring.redis.timeout=0
3. Add the Cache configuration class
@Configuration@EnableCachingPublicClass RedisconfigExtends cachingconfigurersupport{@BeanPublicKeygeneratorKeygenerator() {ReturnNew Keygenerator () {@OverridePublicObjectGenerate(Object target, method, object...params) {StringBuilder SB =New StringBuilder (); Sb.Append (target.GetClass ().GetName ()); Sb.Append (method.GetName ());for (Object obj:params) {sb.Append (obj.ToString ()); }Return SB.ToString (); } }; }@SuppressWarnings ("Rawtypes")@BeanPublicCacheManagerCacheManager(Redistemplate redistemplate) {Rediscachemanager RCM =NewRediscachemanager (redistemplate);Set Cache Expiration TimeRcm.setdefaultexpiration (60);//secreturn RCM; }@BeanPublicRedistemplate<string, string>Redistemplate(Redisconnectionfactory Factory) {Stringredistemplate template =Newstringredistemplate (Factory); Jackson2jsonredisserializer Jackson2jsonredisserializer = new jackson2jsonredisserializer (Object.new objectmapper (); Om.visibility. any); Om. enabledefaulttyping (Objectmapper.non_final); Jackson2jsonredisserializer. setobjectmapper (om), template. setvalueserializer (jackson2jsonredisserializer), template. afterpropertiesset (); return template;}
3, OK, then you can directly use the
@RunWith (Springjunit4classrunner.Class@SpringApplicationConfiguration (Application.ClassPublicClass Testredis {@AutowiredPrivate Stringredistemplate stringredistemplate;@AutowiredPrivate Redistemplate redistemplate;@TestPublic void Test()ThrowsException {stringredistemplate.Opsforvalue ().Set"AAA","111"); Assert.Assertequals ("111", stringredistemplate.Opsforvalue ().Get"AAA")); }@TestPublic void Testobj()ThrowsException {User user=NewUser ("[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. "COM.NEO.F"); if (exists) {System.println ( "exists is true");} else{system.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 (< Span class= "hljs-string" > "/getuser") @Cacheable (Value= "User-key") public User getuser () {User user=userrepository. "AA"); System. out. println ( "If the following does not appear" no cache time to invoke "word and can print out data to indicate the success of the Test"); 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. "UID"); if (uid = = null) {uid = UUID . randomuuid ();} Session. setattribute ( "UID", UID); return session.
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.
Use of Redis in Spring boot