前言 Jetcache缓存可以使用的 CacheType 有 REMOTE, LOCAL, BOTH ;
注解 @Cached 在使用时,可以 CacheType,如果不指定,则默认为 REMOTE。
平台中的缓存注解在各个项目运行时,是无法修改的,并且平台中的缓存注解没有指定 CacheType。
场景 满足不同项目对平台缓存存储方式的自定义配置。
场景一:没有缓存中间件,使用 caffeine 本地缓存。
场景二:有缓存中间件,比如Redis,使用 remote.**.type=REDIS
目的 为了满足不同场景的需要。
实现以下功能:
在注解CacheType=REMOTE 的情况下,实现默认缓存可以由 REMOTE 改为 LOCAL、BOTH。
风险 风险一 在用户需要把缓存注解默认为 CacheType=REMOTE 的数据,改为 BOTH,并且需要主动指定缓存注解 CacheType=REMOTE 的数据,只存到 REMOTE 中。
解决风险 风险一 当前是实现了多个缓存系统(LOCAL、REMOTE),所以需要自定义的缓存中,指定缓存的 area (默认为 default)。
下面是 area 描述的原话:
1 2 3 4 5 /** * If you want to use multi backend cache system, you can setup multi "cache area" in configuration, * this attribute specifies the name of the "cache area" you want to use. * @return the name of cache area */
因为主要目的是修改平台默认的缓存方案,并不是项目中默认的缓存方案,所以只需要处理平台缓存 area 下的 CacheType。
当平台缓存的 area 与 项目中缓存的 area 区分开来时,那么平台的默认缓存就很容易修改了。
实现 实现方案
重写 jetcache下的ConfigMap类,处理 CacheType。
建议修改平台缓存的 area(为了适配一个项目多种缓存系统)。
具体实现 平台中的缓存注解 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 @Service public class CategoryItemServiceImpl extends ServiceImpl <CategoryItemMapper, CategoryItem> implements ICategoryItemService { @Override @Cached(name = "categoryItemList:parentId:",key = "#parentId+''",area="systemo_demo") public List<CategoryItemDTO> loadCategoryItemListByParentId (Long parentId) { LambdaQueryWrapper<CategoryItem> queryWrapper = new LambdaQueryWrapper <>(); queryWrapper.select( CategoryItem::getId, CategoryItem::getParentId, CategoryItem::getItemCode, CategoryItem::getName) .eq(CategoryItem::getParentId,parentId) .eq(CategoryItem::getDelStatus,BaseConstant.NO) .orderByAsc(CategoryItem::getSortIndex); List list = this .list(queryWrapper); return categoryConvert.convertToCategoryItemDTOList(list); } }
systemo_demo是平台内的系统常量
ConfigMap处理默认缓存方式1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public class CustomCacheConfigMap extends ConfigMap { @Override public void putByMethodInfo (String key, CacheInvokeConfig config) { methodInfoMap.put(key, config); CachedAnnoConfig cac = config.getCachedAnnoConfig(); if (cac != null && !CacheConsts.isUndefined(cac.getName())) { if (CacheConsts.DEFAULT_CACHE_TYPE.equals(cac.getCacheType()) && "system.demo" .equals(cac.getArea()) && cacheConfig.getCacheType() != null ) { cac.setCacheType(cacheConfig.getCacheType()); } cacheNameMap.put(cac.getArea() + "_" + cac.getName(), config); } } }
本文地址: https://github.com/maxzhao-it/blog/post/b2db72d0/