Method steps for using redis caching in the SpringBoot project

  • 2020-12-09 00:50:59
  • OfStack

This article introduces the methods and steps of using redis cache in SpringBoot project and shares them with you as follows:

Spring Data Redis encapsulates various operations on the Redis client for us, making it easy to use.

- When Redis operates as a database or message queue, we generally use RedisTemplate to operate

- When Redis is used as a cache, we can use it as an implementation of Spring Cache, using annotations directly

1. An overview of the

Using redis cache effectively in application can improve system performance, especially for query operation, and reduce database pressure effectively.

Refer to the sample project for the specific code

2. Add references

In build gradle to join


compile('org.springframework.boot:spring-boot-starter-data-redis')

SpringBoot automatically introduces ES37en-related jar packages. After adding this reference, you need to install redis locally and start it, otherwise an error will be reported when the program starts.

3. Enable caching with annotations

Enabling redis in SpringBoot is as simple as adding the @EnableCaching annotation to the Application main class and then adding the @Cacheable annotation to the query methods that need to be cache-enabled.


@SpringBootApplication
@EnableCaching
public class DemoApplication implements CommandLineRunner{
...

Query interface:


public interface TestRepository extends JpaRepository<Test, Integer> {
  @Cacheable(value = "testCache")
  public Test findOne(Integer id);
}

The entity class needs to implement the Serializable interface, otherwise the program will report an error because the java object cannot be serialized into redis. redis in SpringBoot uses DefaultSerializer by default, which uses jdk's own serialization method.

There are several serialization methods, and you can refer to the official documentation for specific usage scenarios

1. GenericJackson2JsonRedisSerializer
2. GenericToStringSerializer
3. Jackson2JsonRedisSerializer
4. JacksonJsonRedisSerializer
5. JdkSerializationRedisSerializer
6. OxmSerializer
7. StringRedisSerializer

At this point, our program has the ability to query data from the redis cache, and if you don't mind the aesthetics of KEY stored in redis, that's it.

Beautiful KEY

Carry out our program after  in redis - cli KEY * command, will find key value is 1 pile is similar to the code:

"testCache:\xac\xed\x00\x05sr\x00\x11java.lang.Integer\x12\xe2\xa0\xa4\xf7\x81\x878\x02\x00\x01I\x00\x05valuexr\x00\x10java.lang.Number\x86\xac\x95\x1d\x0b\x94\xe0\x8b\x02\x00\x00xp\x00\x00\x00\x01"
The key value is probably not acceptable to the redis operations staff, so we need to make the key value 1 more attractive, or at least comprehensible.

The reason for the key value above is that the SimpleKey class is adopted by default in spring to generate key for redis.

The solution is also simple. Add the cache configuration and specify how redis will generate key:


@Configuration
public class CacheConfig extends CachingConfigurerSupport {

  @Autowired
  private RedisTemplate redisTemplate;

  @Bean
  public CacheManager cacheManager() {

    redisTemplate.setKeySerializer(new GenericToStringSerializer<Object>(Object.class));

    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
    cacheManager.setDefaultExpiration(3600);
    cacheManager.setUsePrefix(true);
    cacheManager.setCachePrefix(new RedisCachePrefix() {
      private final RedisSerializer<String> serializer = new StringRedisSerializer();
      private final String delimiter = ":";

      public byte[] prefix(String cacheName) {
        return this.serializer
            .serialize(cacheName.concat(this.delimiter));
      }
    });

    return cacheManager;
  }
}

Among them


redisTemplate.setKeySerializer(new GenericToStringSerializer<Object>(Object.class));

This line of code specifies how the key value is generated in redis, the serialization method that converts the java object into a string and stores it in redis.

5. To summarize

In SpringBoot enable redis cache  is very simple, you just need to add a few notes. At the same time, we can increase the cache configuration to make the key value stored in redis readable, rather than a heap of gibboish data.


Related articles: