Springboot (iii) integrated Redis

Source: Internet
Author: User
Tags assert sessions uuid redis server

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 is 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 connections 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 @enablecaching Public classRedisconfig extends cachingconfigurersupport{@Bean Publickeygenerator Keygenerator () {return NewKeygenerator () {@Override PublicObject Generate (Object target, Method method, Object ...)params) {StringBuilder sb=NewStringBuilder ();                Sb.append (Target.getclass (). GetName ());                Sb.append (Method.getname ());  for(Object obj:params) {sb.append (obj.tostring ()); }                returnsb.tostring ();    }        }; } @SuppressWarnings ("Rawtypes") @Bean PublicCacheManager CacheManager (redistemplate redistemplate) {Rediscachemanager RCM=NewRediscachemanager (redistemplate); //Set cache Expiration Time//rcm.setdefaultexpiration ();//seconds        returnRCM; } @Bean PublicRedistemplate<string, string>redistemplate (Redisconnectionfactory Factory) {stringredistemplate template=Newstringredistemplate (Factory); Jackson2jsonredisserializer Jackson2jsonredisserializer=NewJackson2jsonredisserializer (Object.class); Objectmapper om=NewObjectmapper ();        Om.setvisibility (Propertyaccessor.all, JsonAutoDetect.Visibility.ANY);        Om.enabledefaulttyping (ObjectMapper.DefaultTyping.NON_FINAL);        Jackson2jsonredisserializer.setobjectmapper (OM);        Template.setvalueserializer (Jackson2jsonredisserializer);        Template.afterpropertiesset (); returntemplate; }}

3, OK, then you can directly use the

@RunWith (Springjunit4classrunner.class) @SpringApplicationConfiguration (application.class) Public classTestredis {@AutowiredPrivatestringredistemplate stringredistemplate; @AutowiredPrivateredistemplate redistemplate; @Test Public voidtest () throws Exception {Stringredistemplate.opsforvalue ().Set("AAA","111"); Assert.assertequals ("111", Stringredistemplate.opsforvalue ().Get("AAA")); } @Test Public voidTestobj () throws Exception {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 ( +); //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  "   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:

86400*)publicclass  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) Session.getattribute ("uid");         if NULL ) {            = 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.

Springboot (iii) integrated Redis

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.