Springboot (iii): Use of Redis in Spring boot

Source: Internet
Author: User
Tags assert 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 = 0)Spring.redis.database=0# Redis Server Addressspring.redis.host=192.168.0.58# Redis server connection port Span class= "py" >spring.redis.port=6379 # Redis server connection password (default is empty) spring.redis.password= # connection pool Maximum number of connections (using negative values for No limit) # connection pool maximum blocking wait time (with negative value for No limit) =-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) =0          

3. Add the Cache configuration class

@Configuration@EnableCachingPublicClassRedisconfigExtendsCachingconfigurersupport{@BeanPublicKeygeneratorKeygenerator(){ReturnNewKeygenerator(){@OverridePublicObjectGenerate(ObjectTarget,MethodMethod,Object...Params){StringBuilderSb=NewStringBuilder();Sb.Append(Target.GetClass().GetName());Sb.Append(Method.GetName());For(ObjectObj:Params){Sb.Append(Obj.Tostring());}ReturnSb.Tostring();}};}@SuppressWarnings("Rawtypes")@BeanPublicCacheManagerCacheManager(RedistemplateRedistemplate){RediscachemanagerRcm=NewRediscachemanager(Redistemplate);Set Cache Expiration TimeRcm.setdefaultexpiration (60);//secReturnRcm;}@BeanPublicRedistemplate<String,String>Redistemplate(RedisconnectionfactoryFactory){StringredistemplateTemplate=NewStringredistemplate(Factory);Jackson2jsonredisserializerJackson2jsonredisserializer=NewJackson2jsonredisserializer(Object.Class);ObjectmapperOm=NewObjectmapper();Om.Setvisibility(PropertyAccessor.All,Jsonautodetect.Visibility.anyom. (objectmapper. Defaulttyping.jackson2jsonredisserializer. (omtemplate. (jackson2jsonredisserializertemplate. (); return template}             /span>                

3, OK, then you can directly use the

@RunWith(Springjunit4classrunner.Class)@SpringApplicationConfiguration(Application.Class)PublicClassTestredis{@AutowiredPrivateStringredistemplateStringredistemplate;@AutowiredPrivateRedistemplateRedistemplate;@TestPublicvoidTest()ThrowsException{Stringredistemplate.Opsforvalue().Set("AAA","111");Assert.Assertequals("111",Stringredistemplate.Opsforvalue().Get("AAA"));}@TestPublicvoidTestobj()ThrowsException{UserUser=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");BooleanExists=redistemplate. Haskey ( "COM.NEO.F" if (exists) {system out. ( "exists is true" }else{system. Out. ( "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.. (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")StringUid(HttpSessionSession){UuidUid= (uuid) session. ( "UID" if  (uid == null) {uid = uuid. Randomuuid (); } session. ( "UID" uidreturn session. Getid ();               /span>                

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): Use of Redis in Spring boot

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.