Springboot Integrated Redis

Source: Internet
Author: User
Tags redis server port redis server
Springboot Integrated Redis Preface

Redis is a very extensive memory database currently in use, and it supports richer data types than memcached. A brief introduction to the method of using Redis in Springboot. how to use.

1. Introduction of Spring-boot-starter-redis

<!--redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    < Artifactid>spring-boot-starter-data-redis</artifactid>
</dependency>

2, in application.properties to increase the Redis configuration

# using the database (0-15), the default is 0
spring.redis.database=0  
# Redis server address
spring.redis.host=127.0.0.1
# Redis Server connection Port
spring.redis.port=6379  
# Redis Server connection password (default is null)
spring.redis.password=  

3. Use

@Autowired
private stringredistemplate stringredistemplate;

@RequestMapping (value = "/redis/{key}/{value}", method = Requestmethod.get)
@ResponseBody a public
String Redistest (@PathVariable string key, @PathVariable string value) {
    string redisvalue = Stringredistemplate.opsforvalue (). get (key);
    if (Stringutils.isempty (Redisvalue)) {
        stringredistemplate.opsforvalue (). Set (Key,value);
        return operation succeeded. ";
    }

    if (!redisvalue.equals (value)) {
        stringredistemplate.opsforvalue (). Set (Key,value);
        return operation succeeded. ";
    }

    return String.Format ("[key=%s,value=%s] data already exists in Redis.") ", Key,value);
}

An example of random writing.

4, Sentinel mode configuration
The above is a stand-alone configuration, if the master and subordinate, reference:

#redis配置
spring.redis.database=0
spring.redis.password=system
spring.redis.pool.max-idle=10
Spring.redis.pool.min-idle=0
spring.redis.pool.max-active=10
spring.redis.pool.max-wait=-1
Spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes= 192.168.74.135:26379,192.168.74.136:26379

5, Redis all the configuration:

# Redis (redisproperties) spring.redis.cluster.max-redirects= # Maximum number of redirects to follow when executing comma
NDS across the cluster.
spring.redis.cluster.nodes= # comma-separated List of "host:port" pairs to bootstrap from.
Spring.redis.database=0 # Database index used by the connection factory. Spring.redis.url= # Connection URL, would override host, port and password (user'll be ignored), e.g. Redis://user:passwo
rd@example.com:6379 Spring.redis.host=localhost # Redis Server host.
spring.redis.password= # Login Password of the Redis server.
Spring.redis.ssl=false # Enable SSL support. SPRING.REDIS.POOL.MAX-ACTIVE=8 # max number of connections that can is allocated by the pool in a given time.
Use a negative value for no limit. SPRING.REDIS.POOL.MAX-IDLE=8 # max number of "idle" connections in the pool.
Use a negative value to indicate a unlimited number of idle connections. Spring.redis.pool.max-wait=-1 # Maximum amount of time (in milliseconds) a connection allocationShould block before throwing a exception when the pool is exhausted.
Use a negative value to block indefinitely. Spring.redis.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool.
This setting only has a effect if it is positive.
spring.redis.port=6379 # Redis Server port.
spring.redis.sentinel.master= # Name of Redis server.
spring.redis.sentinel.nodes= # comma-separated List of host:port pairs. Spring.redis.timeout=0 # Connection timeout in milliseconds.

6. Use Redis to automatically cache data
You can put some frequently queried data into the Redis cache without querying the database every time.
The above is a manual cache to Redis, which describes how to automatically cache data to Redis.

A. Add a Redis configuration class:

@Configuration @EnableCaching public class redisconfig{@Bean public Keygenerator rediskeygenerator () {RE Turn New Keygenerator () {@Override public object generate (object target, method 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 ();

    }
        }; @Bean public CacheManager CacheManager (@SuppressWarnings ("Rawtypes") redistemplate redistemplate)
    {return new Rediscachemanager (redistemplate);
        @Bean public redistemplate<string, string> redistemplate (Redisconnectionfactory factory) {
        Stringredistemplate template = new Stringredistemplate (factory); Jackson2jsonredisserializerJackson2jsonredisserializer = new Jackson2jsonredisserializer (object.class);
        Objectmapper om = new Objectmapper ();
        Om.setvisibility (Propertyaccessor.all, JsonAutoDetect.Visibility.ANY);
        Om.enabledefaulttyping (ObjectMapper.DefaultTyping.NON_FINAL);
        Jackson2jsonredisserializer.setobjectmapper (OM);
        Template.setvalueserializer (Jackson2jsonredisserializer);
        Template.afterpropertiesset ();
    return template;
 }
}

B. Add annotations to the service method that needs to be cached:

@Cacheable (value = "Usercache") public
TUser FindByID (String ID) {return
    this.userRepository.findOne (ID);
}

In this way, the database will only be queried when there is no corresponding key for Redis.

Let's look at the Redis:

In the picture, the key of the Redis is your argument.

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.