An article takes you to get Spring Cache integration Redis

1. Pre-configuration

First, W build a Springboot project and introduce dependencies:
Spring Web, Spring cache, redis, Spring Security

Insert picture description here
Configure application.properties

spring.redis.host=192.168.176.128
spring.redis.port=6379
#给缓存取一个名字,后面会用到
spring.cache.cache-names=yolo

2. Cache usage

(1) @CacheConfig

This annotation is used on the class to describe the name of the cache used by all methods in the class. Of course, it is not necessary to use this annotation and directly configure the name on the specific cache annotation. The sample code is as follows:

@Service
@CacheConfig(cacheNames = "yolo")
public class UserService {
    
    
}

You can see that the cached keys will all add the name:

Insert picture description here

(2)@Cacheable

This annotation is generally added to the query method to indicate that the return value of a method is cached. By default, the cached key is the method parameter, and the cached value is the method return value. The sample code is as follows:

@Cacheable(key = "#id")
public User getUserById(Integer id,String username) {
    
    
    System.out.println("getUserById");
    return getUserFromDBById(id);
}

When there are multiple parameters, multiple parameters are used as the key by default. If you only need one of the parameters as the key, you can @Cacheablespecify the key through the key attribute in the annotation. The above code means that only the id is used as the cache. Key, if you have complex requirements for the key, you can customize the keyGenerator. Of course, the root object is provided in Spring Cache, which can achieve some complex effects without defining keyGenerator:

Insert picture description here
Example:

@Service
//用来描述该类中所有方法使用的缓存名称
@CacheConfig(cacheNames = "yolo")
public class UserService {
    
    
    //表示将该方法的返回值缓存起来
    @Cacheable
    public User getUserById(Integer id) {
    
    
        System.out.println("getUserById>>>" + id);
        User user = new User();
        user.setId(id);
        return user;
    }
}

Test cache:

Insert picture description here
You can see that the method was executed only once, because the second call was not executed, and the cached result was used.

When the parameters passed by the call are not the same, it will be considered as two different calls:

Insert picture description here
When the key is specified, the judgment will be made according to the difference of the key. If the key is the same two times, it will only be called once:

Although there are multiple parameters here, you can specify a key, such as specifying id as key:
Insert picture description here
you can see that although the passed parameters are different, it is only called once:

Insert picture description here

(3) Custom keyGenerator

If you have complex requirements for the key, you can customize the keyGenerator
For example, the key format I want here is:方法名:参数

//自定义 keyGenerator,将返回值当做 key
@Component
public class MyKeyGenerator implements KeyGenerator {
    
    
    @Override
    public Object generate(Object o, Method method, Object... objects) {
    
    
        //可以根据自己的需求返回 key
        return method.getName() + ":" + Arrays.toString(objects);
    }
}

Insert picture description here
Stored key:

Insert picture description here

(4) @CacheEvict

This annotation is generally added to the delete method. When the data in the database is deleted, the related cached data should also be automatically cleared. When the annotation is used, it can also be configured to be deleted according to certain conditions (condition attribute) or configured to clear all caches. (AllEntries attribute), the sample code is as follows:

  @CacheEvict
    public void deleteUserById(Integer id) {
    
    
        System.out.println("deleteUserById>>>" + id);
    }

You can see that the cache is not used the second time, and it is called again:

Insert picture description here

(5)@CachePut

This annotation is generally added to the update method. When the data in the database is updated, the data in the cache will also be updated. Using this annotation, the return value of the method can be automatically updated to the existing key. The sample code is as follows:

  @CachePut(key = "#user.id")
    public User updateUserById(User user) {
    
    
        return user;
    }

You can see that it was only called once, and the cache was used directly the second time, but the cache at this time is the cache that has been updated.

Insert picture description here

Three, summary

In Spring Boot, using Redis cache, you can either use RedisTemplate to implement it yourself, or you can use this method. This method is a unified interface provided by Spring Cache. The implementation can be either Redis, Ehcache or other support. A standardized caching framework. From this perspective, the relationship between Spring Cache and Redis and Ehcache is like the relationship between JDBC and various database drivers.

Refer to the video of Brother Yu

Guess you like

Origin blog.csdn.net/nanhuaibeian/article/details/108470086