红茶的个人站点

  • 首页
  • 专栏
  • 开发工具
  • 其它
  • 隐私政策
Awalon
Talk is cheap,show me the code.
  1. 首页
  2. 专栏
  3. Spring Boot 学习笔记
  4. 正文

从零开始 Spring Boot 47:缓存

2023年6月22日 1295点热度 0人点赞 0条评论

spring boot

图源:简书 (jianshu.com)

Spring 提供一个简单但使用的缓存(Cache)机制,我们可以利用它来优化代码执行效率。

简单示例

老规矩,我们从一个简单示例开始:

@Service
public class FibonacciService2 {
    @Clock
    public long fibonacci(int n) {
        return doFibonacci(n);
    }
​
    private long doFibonacci(int n) {
        if (n <= 0) {
            throw new IllegalArgumentException("n不能小于等于0");
        }
        if (n <= 2) {
            return 1;
        }
        return this.doFibonacci(n - 2) + this.doFibonacci(n - 1);
    }
}

FibonacciService2用于计算斐波那契数列,具体采用递归方式进行计算,这很消耗时间。

  • @Clock是一个自定义的注解,用一个自定义 AOP 切面来处理,以统计方法的执行时长,感兴趣的可以查看完整代码。

  • 这里将实际的计算逻辑拆分为dodoFibonacci方法(与外部调用方法fibonacci分开),是因为方便统计方法执行时长,以及后期的缓存优化。

编写一个测试用例并执行:

@SpringJUnitConfig(classes = {CacheApplication.class})
@Import(ClockConfig.class)
public class FibonacciService2Tests {
    @Autowired
    FibonacciService2 fibonacciService;
​
    @Test
    void testFibonacci() {
        var result = fibonacciService.fibonacci(40);
        Assertions.assertEquals(102334155L, result);
    }
}

执行结果:

com.example.cache.FibonacciService2.fibonacci() is called, use 211 mills.

执行时长有211毫秒,并且随着计算位数的增加,计算时长会指数增加。

这个问题很明显可以通过缓存来进行优化,因为计算一个高位斐波那契数会涉及低位斐波那契数的重复计算,只要将这些计算缓存起来,就会很快得出一个高位斐波那契数。

要使用 Spring 缓存,需要添加依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

这是 Spring Boot 的方式,如果是 Spring,需要添加不同的依赖,具体可以参考这篇文章。

其次需要给配置类(@Configuration)添加上@EnableCaching注解以启用缓存功能:

@Configuration
@EnableCaching
public class WebConfig {
    // ...
}

要使用缓存,还需要添加一个CacheManager类型的 bean,默认情况下 Spring Boot 会创建一个ConcurrentMapCacheManager 作为CacheManager bean,因此一般不需要手动添加。

如果我们要修改默认创建的ConcurrentMapCacheManager,可以通过定义一个或多个CacheManagerCustomizer<ConcurrentMapCacheManager>类型的 bean 来实现:

@Configuration
@EnableCaching
public class WebConfig {
    @Bean
    CacheManagerCustomizer<ConcurrentMapCacheManager> cacheManagerCustomizer() {
        return cacheManager -> {
            cacheManager.setCacheNames(List.of("fibonacci", "cache2"));
        };
    }
    // ...
}

Spring 会获取这些CacheManagerCustomizer类型的 bean,并利用它们对CacheManager进行初始化。

这个过程由自动配置类CacheAutoConfiguration实现。

可以利用CacheManagerCustomizer设置CacheManager的(多个)缓存名称:

cacheManager.setCacheNames(List.of("fibonacci", "cache2"));

现在修改代码,给需要进行缓存的方法添加上@Cacheable注解:

@Service
public class FibonacciService3 {
    // ...
    @Cacheable("fibonacci")
    protected long doFibonacci(int n) {
        if (n <= 0) {
            throw new IllegalArgumentException("n不能小于等于0");
        }
        if (n <= 2) {
            return 1;
        }
        return this.doFibonacci(n - 2) + this.doFibonacci(n - 1);
    }
}

要注意的是,@Cacheable只能作用于public或protected方法,对于private方法是不起作用的。原因也很简单,和之前介绍过的异步执行(@Async)类似,它们都是通过AOP 实现的,而 AOP 又是通过代理(JDK或CGLIB)实现的。而这里FibonacciService3没有接口,所以显然是使用 CGLIB 代理实现(类继承),因此存在这样的限制。

  • 关于 AOP 实现原理及相应的限制,可以阅读我的这篇文章。

  • 如果对protected方法使用@Cacheable,idea 会有错误提示——@Cacheable只能错用于 public 方法。但实际上在通过 CGLIB 进行代理的情况下,是的确可以对protected方法缓存的,且会正常通过编译并执行。所以这大概是 idea 的一种“粗鲁”提示。

我们可以给@Cacheable注解指定一个(或多个)使用的缓存(@Cacheable("fibonacci")),这里使用的是之前通过CacheManager设置的名称为fibonacci的缓存。

现在是不是可以利用缓存提升代码执行效率了?并不会!

实际运行测试用例就会发现,时间几乎一致,并没有显著提升。

原因是这里进行缓存的方法进行了自调用,我们之前在介绍 AOP 的时候提到过,因为 Spring AOP 通过代理实现,所以默认情况下不能处理“自调用”。

具体到我们这里的示例,fibonacci自调用了doFibonacci,而doFibonacci又对自己进行了递归调用,所以实际上不会触发任何缓存。

当然,我们可以对外部调用方法fibonacci进行缓存:

@Service
public class FibonacciService3 {
    @Clock
    @Cacheable("fibonacci")
    public long fibonacci(int n) {
        return doFibonacci(n);
    }
}

但这样用处不大,仅仅可以缩减“重复获取斐波那契数”的执行效率:

@SpringJUnitConfig(classes = {CacheApplication.class})
@Import(ClockConfig.class)
public class FibonacciService3Tests {
    @Autowired
    FibonacciService3 fibonacciService;
​
    @Test
    void testFibonacci() {
        var result = fibonacciService.fibonacci(40);
        Assertions.assertEquals(102334155L, result);
        var result2 = fibonacciService.fibonacci(40);
        Assertions.assertEquals(result2, result);
        fibonacciService.fibonacci(39);
    }
}

执行结果:

com.example.cache.FibonacciService3.fibonacci() is called, use 214 mills.
com.example.cache.FibonacciService3.fibonacci() is called, use 0 mills.
com.example.cache.FibonacciService3.fibonacci() is called, use 126 mills.

所以,我们要想办法让“中间斐波那契数”的计算能够被缓存。通过之前的文章我们知道,可以通过手动调用代理的方式让“自调用”也能够触发 AOP 的 advice,因此我们可以修改代码:

@Service
public class FibonacciService {
    @Clock
    public long fibonacci(int n) {
        var aopProxy = (FibonacciService) AopContext.currentProxy();
        return aopProxy.doFibonacci(n);
    }
​
    @Cacheable("fibonacci")
    protected long doFibonacci(int n) {
        if (n <= 0) {
            throw new IllegalArgumentException("n不能小于等于0");
        }
        if (n <= 2) {
            return 1;
        }
        var aopProxy = (FibonacciService) AopContext.currentProxy();
        return aopProxy.doFibonacci(n - 2) + aopProxy.doFibonacci(n - 1);
    }
}

要使用AopContext.currentProxy(),还必须修改相关配置:

@Configuration
@EnableCaching
public class WebConfig {
    // ...
    @Bean
    static BeanFactoryPostProcessor forceAutoProxyCreatorToExposeProxy() {
        return (beanFactory) -> {
            if (beanFactory instanceof BeanDefinitionRegistry) {
                BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
                AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
            }
        };
    }
}

现在,所有对doFibonacci方法的调用都被缓存起来了,只要存在“重复调用”,就会查询缓存并直接返回结果。

可以用测试用例检查:

@SpringJUnitConfig(classes = {CacheApplication.class})
@Import(ClockConfig.class)
public class FibonacciServiceTests {
    @Autowired
    FibonacciService fibonacciService;
​
    @Test
    void testFibonacci() {
        var result = fibonacciService.fibonacci(40);
        Assertions.assertEquals(102334155L, result);
        var result2 = fibonacciService.fibonacci(40);
        Assertions.assertEquals(result2, result);
        fibonacciService.fibonacci(39);
    }
}

执行结果:

com.example.cache.FibonacciService.fibonacci() is called, use 4 mills.
com.example.cache.FibonacciService.fibonacci() is called, use 0 mills.
com.example.cache.FibonacciService.fibonacci() is called, use 0 mills.

只有第一次调用(fibonacci方法)花费了一点时间,但与之前相比依然可以忽略不计,而后两次的调用因为使用了缓存结果,所以几乎是不花费时间的。

多缓存

可以给@Cacheable指定多个缓存,默认情况下@Cacheable使用方法参数作为缓存的key。此时只要有一个缓存中有缓存结果,就直接返回。否则执行方法调用,并将结果缓存到所有缓存中。

我们看下面这个例子:

@Service
@Log4j2
public class UserService {
    private final Map<String, String> longNameAddresses = new HashMap<>();
​
    {
        longNameAddresses.put("DavisMiller", "上海南京路15号");
        longNameAddresses.put("RodriguezSmith", "马德里圣玛利亚街101号");
    }
​
    private final Map<String, String> shortNameAddresses = new HashMap<>();
​
    {
        shortNameAddresses.put("LiLei", "北京王府井115号");
        shortNameAddresses.put("XiaoMin", "纽约大十字街11号");
    }
​
    @Cacheable({"addresses1", "addresses2"})
    public String getAddress(@NonNull String name) {
        log.info("query name: %s".formatted(name));
        var proxy = (UserService) AopContext.currentProxy();
        if (name.length() <= 8) {
            return proxy.getShortNameAddress(name);
        }
        return proxy.getLongNameAddress(name);
    }
​
    @Cacheable("addresses1")
    protected String getLongNameAddress(String name) {
        log.info("query long name: %s".formatted(name));
        if (longNameAddresses.containsKey(name)) {
            return longNameAddresses.get(name);
        }
        return null;
    }
​
    @Cacheable("addresses2")
    protected String getShortNameAddress(String name) {
        log.info("query short name: %s".formatted(name));
        if (shortNameAddresses.containsKey(name)) {
            return shortNameAddresses.get(name);
        }
        return null;
    }
}

可能是出于效率的考量,这里将短姓名的地址和长姓名的地址分开存放,并由单独的方法(getLongNameAddress和getShortNameAddress)获取对应的地址信息。并且使用两个独立的缓存进行存储(addresses1和addresses2),方法getAddress被设计成根据姓名长度决定调用哪个方法来完成具体查询。

为了能够提高getAddress的执行效率,对其使用了缓存(@Cacheable({"addresses1", "addresses2"})),也就是说无论getLongNameAddress和getShortNameAddress哪个方法调用过(产生缓存),getAddress都能利用。

其实这个示例存在一点问题,比如如果先调用getAddress查询某个姓名,此时会将这个查询结果同时缓存到2个缓存中,这样无论是调用getLongNameAddress还是getShortNameAddress都能查出结果,而不会返回null,这样不符合方法原本的逻辑。

@CacheEvict

如果大量使用@Cacheable,可能会造成缓存容量增长占用内存的情况。此时我们可以用@CacheEvict来清除缓存内容:

@Service
@Log4j2
public class UserService {
    // ...
    @CacheEvict(value = {"addresses1", "addresses2"}, allEntries = true)
    public String clearCacheAndGetAddress(String name) {
        log.info("clear cache and query name: %s".formatted(name));
        return getAddress(name);
    }
}

调用clearCacheAndGetAddress方法会清除addresses1、addresses2缓存中的所有内容。

如果allEntries=false,仅会清除对应key的缓存信息。

@CachePut

@CachePut和@Cacheable的区别是,后者会先检查缓存中是否有缓存结果,如果有,直接使用,如果没有再执行方法并缓存结果。而@CachePut不论缓存中的情况如何,都会先执行方法调用,然后缓存结果。

示例:

@Service
@Log4j2
public class UserService {
    // ...
    @CachePut(value = {"addresses1","addresses2"})
    public String updateCacheAndGetAddress(String name){
        log.info("update cache and query name: %s".formatted(name));
        return getAddressWithNoCache(name);
    }
}

这里有一个奇怪的现象,如果用@CachePut方法去调用@Cacheable方法,并且它们使用相同的缓存,就可能导致一些奇怪的现象(缓存没有正确被更新为新的内容)。

@Caching

有时候你可能想在一个方法上使用多个缓存注解:

@CacheEvict(value = "addresses1", allEntries = true),
@CacheEvict(value = "addresses2", allEntries = true)
public String clearCacheAndGetAddress(String name) {
    log.info("clear cache and query name: %s".formatted(name));
    return getAddress(name);
}

这是不被允许的,无法通过编译,因为@CacheEvict注解不允许重复使用。

早期的注解都不能重复使用,后期可以通过修改注解定义,让注解允许重复使用,但如果注解定义中缺少相应的声明,就无法这么做。

此时我们要借助@Caching注解:

@Caching(evict = {
    @CacheEvict(value = "addresses1", allEntries = true),
    @CacheEvict(value = "addresses2", allEntries = true)
})
public String clearCacheAndGetAddress(String name) {
    log.info("clear cache and query name: %s".formatted(name));
    return getAddress(name);
}

当然,这里的示例并不恰当,因为完全可以使用一个@CacheEvict实现,只是为了说明@Caching的用途。

@CacheConfig

可以使用@CacheConfig指定类中方法默认使用的缓存:

@Service
@Log4j2
@CacheConfig(cacheNames = {"addresses1", "addresses2"})
public class UserService {
    @Cacheable()
    public String getAddress(@NonNull String name) {
        // ...
    }
    @CachePut()
    public String updateCacheAndGetAddress(String name) {
        log.info("update cache and query name: %s".formatted(name));
        return getAddressWithNoCache(name);
    }
    // ...
}

条件缓存

看示例:

@Service
@Log4j2
@CacheConfig(cacheNames = {"addresses1", "addresses2"})
public class UserService {
    // ...
    @Cacheable(condition = "#name.equals('DavisMiller')")
    public String getAddressWithConditionCache(@NonNull String name){
        return getAddressWithNoCache(name);
    }
}

这个示例中,只有参数name是DavisMiller时结果才会缓存。

当然,更常见的实际示例应当是缓存某个高频分页查询的前N页。

condition条件满足就会被缓存,相应的,可以用unless条件进行排除:

@Service
@Log4j2
@CacheConfig(cacheNames = {"addresses1", "addresses2"})
public class UserService {
    // ...
    @Cacheable(unless = "#result.equals('上海南京路15号')")
    public String getAddressWithConditionCache2(@NonNull String name){
        return getAddressWithNoCache(name);
    }
}

示例中返回结果是上海南京路15号的时候不会缓存,其余结果都会被缓存。

CacheManager

前面我们说过,默认情况下 Spring Boot 会创建一个ConcurrentMapCacheManager作为CacheManager。当然,如果需要的话,我们也可以自行创建:

@Configuration
@EnableCaching
public class WebConfig {
    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        cacheManager.setCaches(List.of(
                new ConcurrentMapCache("fibonacci"),
                new ConcurrentMapCache("addresses1"),
                new ConcurrentMapCache("addresses2")));
        return cacheManager;
    }
    // ...
}

KeyGenerator

查看源码知道,Spring 缓存用于生成缓存 key 的抽象是KeyGenerator接口,并且默认使用一个SimpleKeyGenerator实现:

public abstract class CacheAspectSupport extends AbstractCacheInvoker
    implements BeanFactoryAware, InitializingBean, SmartInitializingSingleton{
    private SingletonSupplier<KeyGenerator> keyGenerator = SingletonSupplier.of(SimpleKeyGenerator::new);
    // ...
}
​
public class SimpleKeyGenerator implements KeyGenerator {
​
    @Override
    public Object generate(Object target, Method method, Object... params) {
        return generateKey(params);
    }
​
    /**
     * Generate a key based on the specified parameters.
     */
    public static Object generateKey(Object... params) {
        if (params.length == 0) {
            return SimpleKey.EMPTY;
        }
        if (params.length == 1) {
            Object param = params[0];
            if (param != null && !param.getClass().isArray()) {
                return param;
            }
        }
        return new SimpleKey(params);
    }
​
}

可以看出,SimpleKeyGenerator是用方法参数来生成缓存 key 的,具体的实现方案是:

  • 如果没有参数(空参数列表),使用SimpleKey.EMPTY作为缓存 key。

  • 只有一个参数,使用该参数作为缓存 key。

  • 有一个以上参数,使用SimpleKey(params)作为缓存 key。

了解这一点后,我们就可以利用SimpleKeyGenerator生成方法缓存对应的 key,并且直接通过Cache对象查询缓存结果。这点对编写测试用例以及在使用 Spring 缓存时出现 bug 的代码调试是很有用的。

下面是我编写的相关工具类,可以做一个示例:

@Component
public class CacheUtil {
    @Autowired
    private CacheManager cacheManager;
    // ...
    /**
     * 获取方法缓存对应的key
     *
     * @param params 方法实参
     * @return 缓存key
     */
    public Object getKey(Object... params) {
        return SimpleKeyGenerator.generateKey(params);
    }
​
    /**
     * 返回对应名称的缓存
     *
     * @param name 缓存名称
     * @return 缓存对象
     */
    public Cache getCache(String name) {
        return cacheManager.getCache(name);
    }
​
    /**
     * 判断指定缓存中是否有某个方法调用的缓存
     *
     * @param cacheName 缓存名称
     * @param params    方法调用实参
     * @return 是否包含该方法调用的缓存
     */
    public boolean containMethodCache(String cacheName, Object... params) {
        return this.getMethodCachedReturn(cacheName, params) != null;
    }
​
    /**
     * 获取指定缓存对象中的方法缓存的返回结果
     *
     * @param cacheName 缓存名称
     * @param params    方法调用实参
     * @return 如果没有缓存,返回null,否则返回ValueWrapper对象(包含缓存结果本身为null的情况)
     */
    public Cache.ValueWrapper getMethodCachedReturn(String cacheName, Object... params) {
        var cache = cacheManager.getCache(cacheName);
        if (cache == null) {
            throw new IllegalArgumentException("没有名称为%s的缓存对象".formatted(cacheName));
        }
        return cache.get(getKey(params));
    }
​
    /**
     * 是否CacheManager中的指定缓存(多个)都有某个方法缓存
     *
     * @param cacheNames 缓存名称(多个)
     * @param params     方法调用实参
     * @return 是否全部拥有对应方法调用的缓存
     */
    public boolean containMethodCacheBoth(List<String> cacheNames, Object... params) {
        for (var cacheName : cacheNames) {
            if (!this.containMethodCache(cacheName, params)) {
                return false;
            }
        }
        return true;
    }
}

需要说明的是,这种方式仅适用于默认的 Spring 缓存实现,如果自定义KeyGenerator实现或者覆盖CacheAspectSupport,这种方式就可能不再适用。需要根据实际的KeyGenerator实现来编写相应的代码。

自定义 KeyGenerator

也可以自定义KeyGenerator,比如默认的SimpleKeyGenerator只使用实参生成 key,因此如果两个方法拥有相同参数列表,且使用同一个缓存对象,它们的缓存结果就会“互相影响”。

显然,这样的情况下你无法用一个缓存对象来缓存“互相之间无关联”的方法,这个问题可以通过添加一个自定义的KeyGenerator来解决:

public class MethodKey implements Serializable {
    private final Object[] params;
    private final Method method;
    // Effectively final, just re-calculated on deserialization
    private transient int hashCode;
    public static final MethodKey EMPTY = new MethodKey();
​
​
    public MethodKey(Method method, Object... params) {
        Assert.notNull(params, "params should be not null.");
        this.params = params.clone();
        this.method = method;
        this.hashCode = this.doHashCode();
    }
​
    @SneakyThrows
    public MethodKey() {
        this.params = new Object[0];
        this.method = this.getClass().getDeclaredMethod("hashCode");
        this.hashCode = this.doHashCode();
    }
​
    public boolean equals(final Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof MethodKey)) {
            return false;
        } else {
            MethodKey other = (MethodKey)o;
            if (!other.canEqual(this)) {
                return false;
            } else if (!Arrays.deepEquals(this.params, other.params)) {
                return false;
            } else {
                Object this$method = this.method;
                Object other$method = other.method;
                if (this$method == null) {
                    if (other$method != null) {
                        return false;
                    }
                } else if (!this$method.equals(other$method)) {
                    return false;
                }
​
                return true;
            }
        }
    }
​
    @Override
    public int hashCode() {
        return this.hashCode;
    }
​
    protected boolean canEqual(final Object other) {
        return other instanceof MethodKey;
    }
​
    private int doHashCode() {
        int result = 1;
        result = result * 59 + Arrays.deepHashCode(this.params);
        Object $method = this.method;
        result = result * 59 + ($method == null ? 43 : $method.hashCode());
        return result;
    }
​
    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
        ois.defaultReadObject();
        // Re-calculate hashCode field on deserialization
        this.hashCode = this.doHashCode();
    }
}
​
public class MethodKeyGenerator implements KeyGenerator {
​
    @Override
    public Object generate(Object target, Method method, Object... params) {
        return generateKey(method, params);
    }
​
    public static Object generateKey(Method method, Object... params) {
        if (params.length == 0) {
            return MethodKey.EMPTY;
        }
        return new MethodKey(method, params);
    }
}

这里的MethodKeyGenerator借鉴了SimpleKeyGenerator,MethodKey借鉴了SimpleKey。

  • 参考SimpleKey,MethodKey同样被设置为可以序列化的(implements Serializable),且同样会在反序列化时重新计算哈希值。个人猜测SimpleKey这么做是为了支持某些外部缓存实现。更多的 Java 对象序列化相关内容,可以阅读我的另一篇文章。

  • MethodKey的 equals 和 doHashCode 方法实现参考了 Lombok 的实现。

与SimpleKeyGenerator不同的是,自定义的MethodKeyGenerator生成缓存 key 的时候不仅包含实参(params),还包含方法对象(method)。这样就能够确保为每个方法生成不同的缓存(即使实参相同)。

要使用自定义的keyGenerator,还需要添加相应的 bean 定义:

@Configuration
@EnableCaching
public class WebConfig {
    // ...
    @Order(Ordered.HIGHEST_PRECEDENCE)
    @Bean
    KeyGenerator keyGenerator(){
        return new SimpleKeyGenerator();
    }
​
    @Bean
    MethodKeyGenerator methodKeyGenerator(){
        return new MethodKeyGenerator();
    }
}

这里不仅添加了MethodKeyGenerator,还添加了SimpleKeyGenerator,且将SimpleKeyGenerator设为最高优先级(@Order(Ordered.HIGHEST_PRECEDENCE))。

这是因为一旦我们添加了自定义的KeyGenerator为 Spring Bean,Spring 缓存就会默认使用这个 bean 作为KeyGenerator,并用于生成缓存 key。如果我们不想这样(保留默认的SimpleKeyGenerator),就需要像上面的示例这样,在添加自定义的MethodKeyGenerator bean 同时添加一个SimpleKeyGenerator bean。

如果想让自定义的KeyGenerator作为全局设置,就不需要这样做。

接下来就可以指定需要缓存的方法使用自定义KeyGenerator:

@Service
@Log4j2
@CacheConfig(cacheNames = {"addresses1", "addresses2"})
public class UserService {
    // ...
    @Cacheable(keyGenerator = "methodKeyGenerator", cacheNames = {"tmp"})
    public String getAddressWithMethodKeyCache(String name){
        String address = this.getAddressWithNoCache(name);
        log.info("query %s and cache %s.".formatted(name, address));
        return address;
    }
​
    @Cacheable(keyGenerator = "methodKeyGenerator", cacheNames = {"tmp"})
    public String getAddressWithMethodKeyCache2(String name){
        String address = this.getAddressWithNoCache(name);
        log.info("query %s and cache %s.".formatted(name, address));
        return address;
    }
}

现在,即使方法getAddressWithMethodKeyCache和getAddressWithMethodKeyCache2,拥有相同的参数列表,同时使用同一个缓存(tmp),且实际调用时传入相同的字符串,但依然会在缓存中产生两条不同的缓存记录,换言之它们的缓存记录是独立的(即使在同一个缓存对象中)。

具体的测试用例请看完整示例代码。

key

除了使用KeyGenerator外,还可以直接指定方法缓存的 key 生成规则:

@EqualsAndHashCode
@Getter
@RequiredArgsConstructor
public class User {
    private final String name;
}
​
@Service
@Log4j2
@CacheConfig(cacheNames = {"addresses1", "addresses2"})
public class UserService {
    // ...
    @Cacheable(cacheNames = {"addresses3"},key = "#user.getName()")
    public String getAddress(User user){
        return this.getAddressWithNoCache(user.getName());
    }
}

这里,方法getAddress接收的是一个User类型的参数,但我们通过@Cacheable(key = "#user.getName()"),指定了其生成缓存 key 的规则是“User对象的name属性”。

测试用例略,感兴趣的可以查看完整代码。

@EnableCaching

经过前边的讨论,我们已经知道 Spring 缓存是通过代理实(AOP)现的,实际上可以通过@EnableCaching注解的属性来改变这一行为。

@EnableCaching注解拥有以下属性:

  • proxyTargetClass:只有在mode为AdviceMode.PROXY时有效,如果为true,将使用CGLIB代理,否则使用 JDK动态代理,默认为false。需要注意的是,修改这个属性后,不仅会影响代理相关功能(@Cacheable等),还会影响到所有使用代理实现的 Spring 功能,比如事务(@Transactional),但一般来说这样不会造成不良影响。

  • mode:可选值有AdviceMode.PROXY和AdviceMode.ASPECTJ,前者用代理实现,后者用 AspectJ 织入实现。默认为AdviceMode.PROXY。

  • order:指定实现代理功能的 AOP advice 在所有 advice 中的执行顺序。

实际使用中发现,如果代理的目标类型没有实现接口,即使当前设置为@EnableCaching(mode=AdviceMode.PROXY,proxyTargetClass=false),依然会使用CGLIB代理实现。

CacheUtil

为了方便使用/调试缓存对象,我编写了一个工具类:

@Component
public class CacheUtil {
    @Autowired
    private CacheManager cacheManager;
​
    /**
     * 打印 CacheManager 中的所有缓存
     */
    public void printCacheManager() {
        var names = cacheManager.getCacheNames();
        names.forEach(this::printCache);
    }
​
    /**
     * 打印 CacheManager 中的指定缓存(必须是 ConcurrentMapCache 实现)
     *
     * @param cacheName 缓存名称
     */
    public void printCache(String cacheName) {
        var cache = cacheManager.getCache(cacheName);
        System.out.println("cache:%s".formatted(cacheName));
        if (cache instanceof ConcurrentMapCache) {
            var cmCache = (ConcurrentMapCache) cache;
            var nCache = cmCache.getNativeCache();
            nCache.forEach((key, value) -> {
                System.out.println("key=%s,value=%s".formatted(key, value));
            });
        }
    }
    // ...
    // KeyGenerator 相关方法,此处省略
    // 清理缓存相关方法,此处省略
}

完整的CacheUtil可以从这里获取。

The End,谢谢阅读。

可以从这里获取本文的完整示例代码。

参考资料

  • 从零开始 Spring Boot 32:AOP II - 红茶的个人站点 (icexmoon.cn)

  • A Guide To Caching in Spring | Baeldung

  • Java编程笔记18:I/O(续) - 红茶的个人站点 (icexmoon.cn)

本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: cache spring 缓存
最后更新:2023年6月25日

魔芋红茶

加一点PHP,加一点Go,加一点Python......

点赞
< 上一篇
下一篇 >

文章评论

取消回复

*

code

COPYRIGHT © 2021 icexmoon.cn. ALL RIGHTS RESERVED.
本网站由提供CDN加速/云存储服务

Theme Kratos Made By Seaton Jiang

宁ICP备2021001508号

宁公网安备64040202000141号