SpringBoot 2.0 Basic Case (08): Integrating Redis database to achieve cache management

Posted by JamieWAstin on Thu, 03 Oct 2019 15:15:05 +0200

Introduction to Redis

In addition to providing excellent automation support for commonly used relational databases, Spring Boot also provides automation configuration support for many NoSQL databases, including Redis, MongoDB, Elastic search. After these cases are sorted out, Git will be uploaded one after another.
Spring Boot version 2, which supports more and more components, supports Redis not only extends the API, but also replaces the dependency of the underlying Jedis and replaces it with Lettuce.
In this case, a Redis database needs to be installed locally.

2. Spring 2.0 Integrated Redis

1. Core Dependence

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2. Configuration file

# port
server:
  port: 8008
spring:
  application:
    # apply name
    name: node08-boot-redis
  # redis configuration
  redis:
    host: 127.0.0.1
    #Timeout connection
    timeout: 1000ms
    jedis:
      pool:
        #Maximum number of connections to database, set 0 for no restrictions.
        max-active: 8
        #Maximum number of waiting connections, set 0 to unlimited
        max-idle: 8
        #Maximize connection setup waiting time. If this time exceeds, an exception will be received. Setting -1 means unlimited.
        max-wait: -1ms
        #Minimum number of waiting connections, set 0 to unlimited
        min-idle: 0

In this way, Redis's environment is successfully configured and the encapsulated API can be used directly.

3. Simple test cases

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@RestController
public class RedisController {
    @Resource
    private StringRedisTemplate stringRedisTemplate ;
    @RequestMapping("/setGet")
    public String setGet (){
        stringRedisTemplate.opsForValue().set("cicada","smile");
        return stringRedisTemplate.opsForValue().get("cicada") ;
    }
    @Resource
    private RedisTemplate redisTemplate ;
    /**
     * Setting Key's validity for 10 seconds
     */
    @RequestMapping("/setKeyTime")
    public String setKeyTime (){
        redisTemplate.opsForValue().set("timeKey","timeValue",10, TimeUnit.SECONDS);
        return "success" ;
    }
    @RequestMapping("/getTimeKey")
    public String getTimeKey (){
        // Here, when Key expires, the string'null'is returned.
        return String.valueOf(redisTemplate.opsForValue().get("timeKey")) ;
    }
}

4. Custom Serialization Configuration

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;
/**
 * Redis To configure
 */
@Configuration
public class RedisConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisConfig.class) ;
    /**
     * Serialization configuration
     */
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate
            (LettuceConnectionFactory  redisConnectionFactory) {
        LOGGER.info("RedisConfig == >> redisTemplate ");
        RedisTemplate<String, Serializable> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

5. Serialization testing

import com.boot.redis.entity.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@RestController
public class SerializeController {
    @Resource
    private RedisTemplate redisTemplate ;
    @RequestMapping("/setUser")
    public String setUser (){
        User user = new User() ;
        user.setName("cicada");
        user.setAge(22);
        List<String> list = new ArrayList<>() ;
        list.add("Primary school");
        list.add("Junior middle school");
        list.add("high school");
        list.add("University");
        user.setEducation(list);
        redisTemplate.opsForValue().set("userInfo",user);
        return "success" ;
    }
    @RequestMapping("/getUser")
    public User getUser (){
        return (User)redisTemplate.opsForValue().get("userInfo") ;
    }
}

3. Source code address

GitHub Address: Know a smile
https://github.com/cicadasmile
 Code Yun Address: Know a smile
https://gitee.com/cicadasmile

Topics: Java Redis Spring Jedis