SpringBoot integrates Redis as a cache

This article needs to be read in conjunction with the previous integration of the default cache component (the previous caching enabled annotations are not described here) SpringBoot’s default cache usage

First, the simplest way

Introduce Redis dependencies directly into poM files:

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

Set redis IP address and port number in the configuration file:

spring:
  redis:
    host: 192.16837.100.
    port: 6379
Copy the code

And implement Serializable interface for the entity class to be cached, you can initially use Redis to store cached data.

Because SpringBoot default SimpleCacheConfiguration as the default configuration, automatically generate ConcurrentMapCacheManager as CacheManager, and after joining the reliance of the redis, CacheManager becomes the RedisCacheManager of its Redis, so you can simply use Redis as a cache component without much configuration.

But there is a problem: the stored data is not in JSON format and is difficult to read:

To solve this problem, use the following method:

2. Customize RedisCacheManager

Add a custom RedisCacheManager to the IOC container using @bean annotation in the configuration class instead of the default, set the storage rules, convert the object data to JSON format, so that the object is stored in Redis in JSON format, more clear and easy to read:

Custom RedisCacheManager:

@Configuration
public class MyRedisConfiguration {

    @Bean
    RedisCacheManager cacheManager( RedisConnectionFactory redisConnectionFactory) {
        // Use the default configuration for caching
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        / / use GenericJackson2JsonRedisSerializer as the serializer
        config = config.serializeValuesWith(
                RedisSerializationContext.SerializationPair.fromSerializer(
                        new GenericJackson2JsonRedisSerializer()));
        RedisCacheManager.RedisCacheManagerBuilder builder =
                RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(config);

        returnbuilder.build(); }}Copy the code

When storing data at this time, you can find that objects in Redis are stored in JSON format, and there is no problem reading cache.