应用缓存的目标就是进步性能,明天码哥带大家实际使用 spring-boot-starter-cache 形象的缓存组件去集成本地缓存性能之王 Caffeine

大家须要留神的是:in-memeory 缓存只适宜在单体利用,不适宜与分布式环境

分布式环境的状况下须要将缓存批改同步到每个节点,须要一个同步机制保障每个节点缓存数据最终统一。

Spring Cache 是什么

不应用 Spring Cache 形象的缓存接口,咱们须要依据不同的缓存框架去实现缓存,须要在对应的代码外面去对应缓存加载、删除、更新等。

比方查问咱们应用旁路缓存策略:先从缓存中查问数据,如果查不到则从数据库查问并写到缓存中。

伪代码如下:

public User getUser(long userId) {    // 从缓存查问    User user = cache.get(userId);    if (user != null) {        return user;    }    // 从数据库加载    User dbUser = loadDataFromDB(userId);    if (dbUser != null) {        // 设置到缓存中        cache.put(userId, dbUser)    }    return dbUser;}

咱们须要写大量的这种繁琐代码,Spring Cache 则对缓存进行了形象,提供了如下几个注解实现了缓存治理:

  • @Cacheable:触发缓存读取操作,用于查询方法上,如果缓存中找到则间接取出缓存并返回,否则执行指标办法并将后果缓存。
  • @CachePut:触发缓存更新的办法上,与 Cacheable 相比,该注解的办法始终都会被执行,并且应用办法返回的后果去更新缓存,实用于 insert 和 update 行为的办法上。
  • @CacheEvict:触发缓存生效,删除缓存项或者清空缓存,实用于 delete 办法上。

除此之外,形象的 CacheManager 既能集成基于本地内存的单体利用,也能集成 EhCache、Redis 等缓存服务器。

最不便的是通过一些简略配置和注解就能接入不同的缓存框架,无需批改任何代码。

集成 Caffeine

码哥带大家应用注解形式实现缓存操作的形式来集成,残缺的代码请拜访 github:https://github.com/MageByte-Z...,在 pom.xml 文件增加如下依赖:

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-cache</artifactId></dependency><dependency>    <groupId>com.github.ben-manes.caffeine</groupId>    <artifactId>caffeine</artifactId></dependency>

应用 JavaConfig 形式配置 CacheManager

@Slf4j@EnableCaching@Configurationpublic class CacheConfig {    @Autowired    @Qualifier("cacheExecutor")    private Executor cacheExecutor;    @Bean    public Caffeine<Object, Object> caffeineCache() {        return Caffeine.newBuilder()                // 设置最初一次写入或拜访后通过固定工夫过期                .expireAfterAccess(7, TimeUnit.DAYS)                // 初始的缓存空间大小                .initialCapacity(500)                // 应用自定义线程池                .executor(cacheExecutor)                .removalListener(((key, value, cause) -> log.info("key:{} removed, removalCause:{}.", key, cause.name())))                // 缓存的最大条数                .maximumSize(1000);    }    @Bean    public CacheManager cacheManager() {        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();        caffeineCacheManager.setCaffeine(caffeineCache());        // 不缓存空值        caffeineCacheManager.setAllowNullValues(false);        return caffeineCacheManager;    }}

筹备工作搞定,接下来就是如何应用了。

@Slf4j@Servicepublic class AddressService {    public static final String CACHE_NAME = "caffeine:address";    private static final AtomicLong ID_CREATOR = new AtomicLong(0);    private Map<Long, AddressDTO> addressMap;    public AddressService() {        addressMap = new ConcurrentHashMap<>();        addressMap.put(ID_CREATOR.incrementAndGet(), AddressDTO.builder().customerId(ID_CREATOR.get()).address("地址1").build());        addressMap.put(ID_CREATOR.incrementAndGet(), AddressDTO.builder().customerId(ID_CREATOR.get()).address("地址2").build());        addressMap.put(ID_CREATOR.incrementAndGet(), AddressDTO.builder().customerId(ID_CREATOR.get()).address("地址3").build());    }    @Cacheable(cacheNames = {CACHE_NAME}, key = "#customerId")    public AddressDTO getAddress(long customerId) {        log.info("customerId:{} 没有走缓存,开始从数据库查问", customerId);        return addressMap.get(customerId);    }    @CachePut(cacheNames = {CACHE_NAME}, key = "#result.customerId")    public AddressDTO create(String address) {        long customerId = ID_CREATOR.incrementAndGet();        AddressDTO addressDTO = AddressDTO.builder().customerId(customerId).address(address).build();        addressMap.put(customerId, addressDTO);        return addressDTO;    }    @CachePut(cacheNames = {CACHE_NAME}, key = "#result.customerId")    public AddressDTO update(Long customerId, String address) {        AddressDTO addressDTO = addressMap.get(customerId);        if (addressDTO == null) {            throw new RuntimeException("没有 customerId = " + customerId + "的地址");        }        addressDTO.setAddress(address);        return addressDTO;    }    @CacheEvict(cacheNames = {CACHE_NAME}, key = "#customerId")    public boolean delete(long customerId) {        log.info("缓存 {} 被删除", customerId);        return true;    }}

应用 CacheName 隔离不同业务场景的缓存,每个 Cache 外部持有一个 map 构造存储数据,key 可用应用 Spring 的 Spel 表达式。

单元测试走起:

@RunWith(SpringRunner.class)@SpringBootTest(classes = CaffeineApplication.class)@Slf4jpublic class CaffeineApplicationTests {    @Autowired    private AddressService addressService;    @Autowired    private CacheManager cacheManager;    @Test    public void testCache() {        // 插入缓存 和数据库        AddressDTO newInsert = addressService.create("南山小道");        // 要走缓存        AddressDTO address = addressService.getAddress(newInsert.getCustomerId());        long customerId = 2;        // 第一次未命中缓存,打印 customerId:{} 没有走缓存,开始从数据库查问        AddressDTO address2 = addressService.getAddress(customerId);        // 命中缓存        AddressDTO cacheAddress2 = addressService.getAddress(customerId);        // 更新数据库和缓存        addressService.update(customerId, "地址 2 被批改");        // 更新后查问,仍然命中缓存        AddressDTO hitCache2 = addressService.getAddress(customerId);        Assert.assertEquals(hitCache2.getAddress(), "地址 2 被批改");        // 删除缓存        addressService.delete(customerId);        // 未命中缓存, 从数据库读取        AddressDTO hit = addressService.getAddress(customerId);        System.out.println(hit.getCustomerId());    }}

大家发现没,只须要在对应的办法上加上注解,就能欢快的应用缓存了。须要留神的是, 设置的 cacheNames 肯定要对应,每个业务场景应用对应的 cacheNames。

另外 key 能够应用 spel 表达式,大家重点能够关注 @CachePut(cacheNames = {CACHE_NAME}, key = "#result.customerId"),result 示意接口返回后果,Spring 提供了几个元数据间接应用。

名称地点形容例子
methodName根对象被调用的办法的名称#root.methodName
method根对象被调用的办法#root.method.name
target根对象被调用的指标对象#root.target
targetClass根对象被调用的指标的类#root.targetClass
args根对象用于调用指标的参数(作为数组)#root.args[0]
caches根对象运行以后办法的缓存汇合#root.caches[0].name
参数名称评估上下文任何办法参数的名称。如果名称不可用(可能是因为没有调试信息),则参数名称也可在#a<#arg> where#arg代表参数索引(从 开始0)下取得。#iban#a0(您也能够应用#p0#p<#arg>表示法作为别名)。
result评估上下文办法调用的后果(要缓存的值)。仅在unless 表达式、cache put表达式(计算key)或cache evict 表达式(when beforeInvocationis false)中可用。对于反对的包装器(例如 Optional),#result指的是理论对象,而不是包装器。#result

外围原理

Java Caching定义了5个外围接口,别离是 CachingProvider, CacheManager, Cache, EntryExpiry

外围类图:

  • Cache:形象了缓存的操作,比方,get()、put();
  • CacheManager:治理 Cache,能够了解成 Cache 的汇合治理,之所以有多个 Cache,是因为能够依据不同场景应用不同的缓存生效工夫和数量限度。
  • CacheInterceptor、CacheAspectSupport、AbstractCacheInvoker:CacheInterceptor 是一个AOP 办法拦截器,在办法前后做额定的逻辑,比方查问操作,先查缓存,找不到数据再执行办法,并把办法的后果写入缓存等,它继承了CacheAspectSupport(缓存操作的主体逻辑)、AbstractCacheInvoker(封装了对 Cache 的读写)。
  • CacheOperation、AnnotationCacheOperationSource、SpringCacheAnnotationParser:CacheOperation定义了缓存操作的缓存名字、缓存key、缓存条件condition、CacheManager等,AnnotationCacheOperationSource 是一个获取缓存注解对应 CacheOperation 的类,而SpringCacheAnnotationParser 是解析注解的类,解析后会封装成 CacheOperation 汇合供AnnotationCacheOperationSource 查找。

CacheAspectSupport:缓存切面反对类,是CacheInterceptor 的父类,封装了所有的缓存操作的主体逻辑。

次要流程如下:

  1. 通过CacheOperationSource,获取所有的CacheOperation列表
  2. 如果有@CacheEvict注解、并且标记为在调用前执行,则做删除/清空缓存的操作
  3. 如果有@Cacheable注解,查问缓存
  4. 如果缓存未命中(查问后果为null),则新增到cachePutRequests,后续执行原始办法后会写入缓存
  5. 缓存命中时,应用缓存值作为后果;缓存未命中、或有@CachePut注解时,须要调用原始办法,应用原始办法的返回值作为后果
  6. 如果有@CachePut注解,则新增到cachePutRequests
  7. 如果缓存未命中,则把查问后果值写入缓存;如果有@CachePut注解,也把办法执行后果写入缓存
  8. 如果有@CacheEvict注解、并且标记为在调用后执行,则做删除/清空缓存的操作

明天就到这了,分享一些工作小技巧给大家,前面码哥会分享如何接入 Redis ,并且带大家实现一个基于 Sping Boot 实现一个 Caffeine 作为一级缓存、Redis 作为二级缓存的分布式二级缓存框架。

咱们下期见,大家能够在评论区叫我靓仔么?不叫也行,点赞分享也是激励。

参考资料

[1]https://segmentfault.com/a/11...

[2]https://docs.spring.io/spring...