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.# Redis Server connection PortSpring. 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 (use negative value to indicate no limit)Spring. Redis. Pool. Max-wait=-1  # Maximum idle connections in the connection poolSpring. Redis. Pool. Max-idle=8  # Minimum idle connections in the connection poolSpring. Redis. Pool. Min-idle=0  # Connection time-out (milliseconds)Spring. Redis. Timeout=0  

3. Add the Cache configuration class

@Configuration@EnableCaching Public  class redisconfig extends cachingconfigurersupport{    @Bean     PublicKeygeneratorKeygenerator() {return NewKeygenerator () {@Override             PublicObjectGenerate(Object target, 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     PublicCacheManagerCacheManager(Redistemplate redistemplate) {Rediscachemanager RCM =NewRediscachemanager (redistemplate);//Set cache expiration Time        //rcm.setdefaultexpiration (60);//sec        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  class testredis {    @Autowired    PrivateStringredistemplate stringredistemplate;@Autowired    PrivateRedistemplate redistemplate;@Test     Public void Test()throwsException {Stringredistemplate.opsforvalue (). Set ("AAA","111"); Assert.assertequals ("111", Stringredistemplate.opsforvalue (). Get ("AAA")); }@Test     Public 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 ( +);//redistemplate.delete ("com.neo.f");        BooleanExists=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")publicgetUser() {    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@EnableRedisHttpSession86400*30)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 uid = (UUID) session.getAttribute("uid");        ifnull) {            uid = UUID.randomUUID();        }        session.setAttribute("uid", uid);        return session.getId();    }

Sign in to Redis input keys ‘*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:)

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.