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

Time:2019-8-13
This article source code
Git Hub: Know a smile
https://github.com/cicadasmile/spring-boot-base

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.
This case requires a Redis database 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:
    # Application Name
    name: node08-boot-redis
  # redis configuration
  redis:
    host: 127.0.0.1
    # Timeout connection
    timeout: 1000ms
    jedis:
      pool:
        # Maximum number of connections to the database, set 0 to unlimited
        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 configuration
 */
@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 high 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/spring-boot-base
Code Yun Address: Know a smile
https://gitee.com/cicadasmile/spring-boot-base

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

Recommended Today

Protocol basis: use telnet to learn IMAP protocol

IMAP introduction IMAPThe full name is Internet Mail Access Protocol, or Interactive Mail Access ProtocolPOP3Similar to one of the mail access standard protocols. The difference is, it’s onIMAPAfter that, the e-mail you received from the e-mail client remains on the server, and the operations on the client will be fed back to the server, such […]