当我们日常开发的时候,总会遇到一些缓存问题,说白了就是把项目中一些数据量较大且轻易不改动的数据放入缓存,以便后续请求可以迅速响应。因此我们可以使用redis作为缓存中间件,我认为使用redis也还是从俩个方面考虑:性能和并发。然后就是ace-cache基于spring boot上的注解缓存,自带轻量级缓存管理页面,比spring cache更轻量的缓存,支持单个缓存设置过期时间,可以根据前缀移除缓存。采用fastjson序列化与反序列化,以json串存于缓存之中,ace-cache可以快速用于日常的spring boot应用之中。
然后我记录下在项目中该如何启动缓存:
1.POM.xml 文件中添加ace-cache依赖和redis依赖(Spring Boot)
org.springframework.boot
spring-boot-starter-data-redis
com.github.wxiaoqi
ace-cache
0.0.2
2.缓存配置
配置redis数据源,application.yml文件:#redis-cache 相关
redis:
pool:
maxActive: 300
maxIdle: 100
maxWait: 1000
host: 127.0.0.1
port: 6379
password:
timeout: 2000
# 服务或应用名
sysName: ace
enable: true
database: 0
3.开启缓存
开启AOP扫描:@EnableAceCache
在Service上进行@Cache注解或@CacheClear注解@Override
@Cacheable(value = "dataDictCache", key = "'petstore:dataDict:all'")
public List getAll() {
return dataDictMapper.selectAll();
}
4.注解说明
(1)配置缓存@cache注解参数类型说明key字符串缓存表达式,动态运算出key
expires×××缓存时长,单位:分钟
desc描述缓存说明
parserClass extends ICacheResultParser>缓存返回结果自定义处理类
generatorClass extends IKeyGenerator>缓存键值自定义生成类
(2)清除缓存@cacheclear注解参数类型说明pre字符串清除某些前缀key缓存
key字符串清除某个key缓存
keys字符串数组清除某些前缀key缓存
generatorClass extends IKeyGenerator>缓存键值自定义生成类
(3)默认key动态表达式说明表达式举例说明举例@Cache(key="user:{1}")
public User getUserByAccount(String account){1}表示获取第一个参数值
{2}表示获取第二个参数值
……依此类推若:account = ace,则:key = user:ace
@CacheClear(pre="user{1.account}")
User saveOrUpdate(User user){1}表示获取第一个参数值
{1.xx}表示获取第一个参数中的xxx属性若:account=ace,则:key = user:ace