Spring Cache Abstraction

Understanding the Cache Abstraction

At its core, the cache abstraction applies caching to Java methods, thus reducing the number of executions based on the information available in the cache.

Spring提供了一种作用在方法上的缓存抽象,从而减少方法的执行次数。

As with other services in the Spring Framework, the caching service is an abstraction (not a cache implementation). This abstraction is materialized by the org.springframework.cache.Cache and org.springframework.cache.CacheManager interfaces.

缓存抽象只是一套接口,也就是操作规范,需要具体的缓存提供者去实现。

Declarative Annotation-based Caching

For caching declaration, Spring’s caching abstraction provides a set of Java annotations:

  • @Cacheable: 如果缓存没有命中则调用方法,然后缓存结果,以便下次直接返回缓存的结果.
  • @CachePut: 更新缓存
  • @CacheEvict: 从缓存中移除某条记录,或者清空缓存
  • @EnableCaching: 启用缓存

The caching abstraction uses a simple KeyGenerator based on the following algorithm:

  • If no parameters are given, return SimpleKey.EMPTY.
  • If only one parameter is given, return that instance.
  • If more than one parameter is given, return a SimpleKey that contains all parameters.

缓存的KEY值是根据方法入参生成的

在并发且没命中缓存的场景下,方法会被多线程并发执行。如果打开同步开关 sync=true,那么,只有一个线程去执行方法,而其他线程会被阻塞,直到能从缓存中拿到执行结果。

Integration with

Spring Boot 缓存抽象的默认实现是 ConcurrentMapCacheManager + ConcurrentMap。如果要使用 Caffeine,则需要引入依赖:implementation(“com.github.ben-manes.caffeine:caffeine:3.1.6”)

Coding

@Component
@CacheConfig(cacheNames = "mooncake")
public class HelloServiceImpl implements HelloService {
    @Cacheable
    @Override
    public String hello(String name) {
        System.out.println("...method hello inside...");
        return String.format("Hello %s, My name is Spring Cache.", name);
    }

    @CachePut
    @Override
    public String update(String name) {
        System.out.println("...method update inside...");
        return String.format("Hallo %s, I am Spring Cache.", name);
    }

    @CacheEvict(beforeInvocation = true, allEntries = true)
    @Override
    public void clearCache() {
        System.out.println("...method clearCache inside...");
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值