跳至主要內容

CacheTimeOut

Mango Crisp2024年12月19日大约 3 分钟代码笔记后端JavaSpringBootSpring Taybct开发框架注解

CacheTimeOut

由于@Cacheable注解暂时是没有可以支持单独设置某个缓存数据的缓存时长,所以才开发了这个注解

参数说明

参数类型必须默认说明
cacheNameString缓存名
keyString缓存键
timeoutlong60L超时时间
timeUnitlongTimeUnit.SECONDS时间单位
conditionString""缓存条件
unlessString""对返回结果做处理的条件
removeConditionString""删除 key 的条件
updateConditionString""更新 key 的条件
updateObjectString""参数名

key (SpEL)

SqEL 表达式获取 key 名,在查询参数里面去获取,可以是多个 key,使用,隔开

condition (SpEL)

缓存条件,与 @Cacheable 里面的 condition 一样,用来判定是否决定要缓存数据 这里要求表达式最终得到的结果要是一个 boolean 即 "true" 或者 "false",不过不管怎么样,只要不是 "true" 或者 "" 就都不会缓存

unless (SpEL)

当 unless 指定的条件为 true ,方法的返回值就不会被缓存,这里可以使用 #result 来引用返回结果

removeCondition (SpEL)

删除 key 的条件,即当条件为 true 的时候,删除 key,并且不再执行缓存操作

updateCondition (SpEL)

更新 key 的条件,即当条件为 true 的时候更新 key,并且直接返回

updateObject

更新的对象的参数名,这里如果不指定,默认拿第一个参数

使用说明

SpEL 表达式(官网)
SpEL 表达式(中文)

所有的缓存条件的判断顺序是:

condition < removeCondition < updateCondition < key < unless

所以,removeCondition 和其他的条件如果使用了,后面的条件就无效了

使用示例
    @CacheTimeOut(cacheName = "taybct:test", key = "#id", condition = "!#id.equals('1')", unless = "#result.getId()==3L", timeout = 90L)
    public SysUser getUser(String id) {
        SysUser sysUser = new SysUser();
        sysUser.setUsername("小明");
        sysUser.setId(Long.valueOf(id));
        return sysUser;
    }
    @CacheTimeOut(cacheName = "taybct:test", key = "#user.getId()", condition = "#user.getId()!=1L"
            , updateCondition = "true", updateObject = "user", unless = "#result==false", timeout = 90L)
    public boolean saveOrUpdateUser(SysUser user) {
        return false;
    }
    @CacheTimeOut(cacheName = "taybct:test", key = "T(cn.hutool.core.util.StrUtil).join(',', #id)", removeCondition = "true"
            , unless = "#result==false")
    public boolean deleteUser(Set<String> id) {
        return true;
    }

配置

可以重写框架的默认实现来使用合适的缓存机制CacheTimeOutMethodInterceptor

如果你有问题
请联系我!