①优雅的缓存框架:SpringCache入门

53 阅读1分钟

初识SpringCache

SpringCache可以实现 不侵入业务代码 实现方法级缓存结果。

体验SpringCache

以下注解的cacheNames均可配置在类上:@CacheConfig(cacheNames = "xxx"),这样方法上就不需要写cacheNames

Cacheable注解

Cacheable类似于map的computeIfAbsent,即若不存在则执行计算并put到map中

/**
 * getById是通过id查询PermDO,使用了Cacheable注解之后,可以先从缓存取值,
 * 若不存在再执行此方法查询,并缓存结果,即使是null也可以缓存(取决于你对SpringCache的配置)
 */
@Cacheable(cacheNames = "perm", key = "#id")
public PermDO getById(String id) {
   return super.getById(id);
}

CachePut注解

CachePut类似于map.put,无论如何都执行目标方法并把返回值put到缓存中

/**
 * 
 */
@Cacheable(cacheNames = "perm", key = "#id")
public UserDO getById(String id) {
    UserDO userDO = super.getById(id);
    if (userDO == null) {
        return null;
    }
    getProxy().putUserNameCache(userDO.getUsername(), userDO);
    return userDO;
}

public UserServiceImpl getProxy() {
    return (UserServiceImpl) AopContext.currentProxy();
}


@CachePut(cacheNames = "perm", key = "'userName:' + #userName")
public UserDO putUserNameCache(String userName, UserDO model) {
    return model;
}

Caching注解

Caching是由于Cacheable、CachePut、CacheEvict不支持在一个方法上同时重复出现。

CacheEvict注解

CacheEvict类似于map.remove

/**
 * 数据库对象更新操作后调用此方法则删除对应的缓存,方法体为空,若未缓存模块,就相当于啥也没发生。
 */
@Caching(evict = {
        @CacheEvict(key = "#p0.id"),
        @CacheEvict(key = "'key:' + #p0.permKey"),
        @CacheEvict(key = "'list'"),
})
protected void afterUpdate(PermDO paramDO, PermDO modelDO) { }

SpringCache注解的key属性是SpEL表达式,上下文中会有参数列表信息。

下一篇: ②优雅的缓存框架:SpringCache的序列化配置优化

以上代码来源: 后端代码:github.com/L1yp/van-te…

前端代码:github.com/L1yp/van-te…

点击链接加入群聊:【Van交流群】