业务场景中经常需要使用数据库中的数据,但多次调用数据库会对性能产生影响,存入REDIS
或者其他中间件面临过期后如何初始化或者新数据如何加载等问题,特定场景下可以使用@Cacheable
。
先上依赖(以下使用的springboot
版本较老,而且项目使用的是gradle
,需要新版本依赖或者MAVEN
的直接去https://mvnrepository.com
拉就行)
compile('org.ehcache:ehcache:3.3.1')
compile("org.springframework.boot:spring-boot-starter-cache")
在启动类加上@EnableCaching
注解
创建一个xml
文件取名ehcache3.xml
,添加一下内容
<?xml version="1.0" encoding="UTF-8"?>
<config
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns='http://www.ehcache.org/v3'
xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd">
<cache-template name="resources">
<expiry>
<ttl unit="minutes">5</ttl>
</expiry>
<heap unit="entries">10000</heap>
</cache-template>
<cache alias="test" uses-template="resources"/>
</config>
cache-template
是模板,里面可以设置过期时间等其他参数,需要的自行查阅。
cache
是具体的使用了,alias
对应类里面的名字。
以下是具体的类
@Cacheable(cacheNames = "test", key = "'testTry'",unless = "#result==null")
public Map<String, Integer> getData()
{
Map<String, Integer> map = new HashMap<>();
//数据库或其他逻辑
Log.info("我进入方法啦!!!!!")
return map;
}
cacheNames
对应xml
文件的alias
,key
暂时不知道啥用有待研究,方法里面就是具体逻辑了,可以打日志,看过期时间内多次调用是不是只打一行日志就知道有没有走内存了。