redis learning notes SpringBoot integration implementation

Posted by praveenbabur on Tue, 18 Jan 2022 03:50:13 +0100

preface

Spring Boot is a new framework provided by pivot team. It is designed to simplify the initial construction and development process of new spring applications. The framework uses a specific way to configure, so that developers no longer need to define templated configurations. In this way, Spring Boot is committed to becoming a leader in the booming field of rapid application development.

Tip: the following is the main content of this article (spring boot integrates redis), and the following cases are for reference

1, What is redis?

Redis (Remote Dictionary Server), i.e. remote dictionary service, is an open source log type key value database written in ANSI C language, supporting network, memory based and persistent, and provides API s in multiple languages. Since March 15, 2010, the development of redis has been hosted by VMware. Since May 2013, the development of redis has been sponsored by pivot.

Redis is an open-source key value storage system, which is similar to memcached. It supports relatively more value types, including string (string), list (linked list), set (set), zset(sorted set -- ordered set) and hash (hash type). These data types support push/pop, add/remove, intersection, union, difference and richer operations, Moreover, these operations are atomic. On this basis, redis supports sorting in different ways. Like memcached, in order to ensure efficiency, the data is cached in memory. The difference is that redis will periodically write the updated data to disk or write the modification operation to the additional record file, and realize master-slave synchronization on this basis.

2, Use steps

1. Install redis

See my other article for details redis installation tutorial

2. Spring boot integrates redis

2.1 creating a Springboot project

2.2 project related configuration

Introducing maven dependency

<!-- spring2.X integrate redis what is needed common-pool2-->
 		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.0</version>
        </dependency>
           <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.11.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.4</version>
        </dependency>

application.properties configuration

#Redis server address
spring.redis.host=Your server address
#Redis server connection port
spring.redis.port=6379
#Redis database index (0 by default)
spring.redis.database= 0
#Connection timeout (MS)
spring.redis.timeout=1800000
#Maximum number of connections in the connection pool (negative value indicates no limit)
spring.redis.lettuce.pool.max-active=20
#Maximum blocking waiting time (negative number indicates no limit)
spring.redis.lettuce.pool.max-wait=-1
#Maximum free connections in the connection pool
spring.redis.lettuce.pool.max-idle=5
#Minimum free connections in connection pool
spring.redis.lettuce.pool.min-idle=0

2.3 create a configuration class RedisConfig

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


import java.time.Duration;

@EnableCaching
//Enable cache
@Configuration
//Configuration class annotation
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = 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.setConnectionFactory(factory);
//key serialization method
        template.setKeySerializer(redisSerializer);
//value serialization
        template.setValueSerializer(jackson2JsonRedisSerializer);
//value hashmap serialization
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//Solve the problem of query cache conversion exception
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
// Configure serialization (solve the problem of garbled code), and the expiration time is 600 seconds
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

2.4 create test controller class RedisTestController

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisTestController {
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("hello_word")
    public String testRedis(){
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //Set the value to redis
        valueOperations.set("test","hello word!");
        //Fetch the value from redis
        String name = (String)valueOperations.get("test");
        return  name;
    }
}


2.4 start project verification

Because the project has no port number configured, it defaults to port 8080

Enter redis client authentication

summary

The above describes the basic process of how to use idea to integrate redis. If there is anything bad, please give me more advice.

Topics: Java Redis Spring Boot