輕量級的緩存框架Ehcache實現其功能。從如下幾點切入:java
導入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Ehcache 座標 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>redis
(2)spring
新建ehcache.xml配置文件
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStore path="java.io.tmpdir/ehcache"/>
<!--defaultCache:echcache的默認緩存策略 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<cache name="users"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</cache>
</ehcache>
而後再經過application.properties配置下
spring.cache.ehcache.config=classpath:ehcache.xml數據庫
(3)api
啓動類上添加@EnableCaching
在寫一個能夠擴展的配置類
/**
* 開啓緩存配置
*
* @author zhangyi
* @date 2018/12/13 15:47
*/
@Configuration
public class EhCacheConfig {
}緩存
(4)app
在類上添加緩存配置,方法上添加緩存操做
@Service
@CacheConfig(cacheNames = "users")
public class UserServiceImpl implements UserService{
@Cacheable(value = "users")
@Override
public List<User> getAllUser(){
List<User> list = new ArrayList<>();
for(int i = 0; i < 5; i++) {
User user = new User();
user.setUserName(String.valueOf(i+Math.random()*10));
user.setPassWord(String.valueOf(i));
list.add(user);
}
System.out.println("模擬數據庫查詢... 過程");
return list;
}
}框架
result:dom
第一次查詢
模擬數據庫查詢... 過程
8.339899184231392--0
4.358651013143946--1
4.244988713811452--2
9.693692145368964--3
8.744268864524635--4
第二次查詢
8.339899184231392--0
4.358651013143946--1
4.244988713811452--2
9.693692145368964--3
8.744268864524635--4
第三次查詢
8.339899184231392--0
4.358651013143946--1
4.244988713811452--2
9.693692145368964--3
8.744268864524635—4分佈式
簡單的三步走,後續的緩存一致性經過 CachePut CacheEvent來控制數據庫和緩存數據之間的同步性
第一次查詢是經過執行serverImpl中方法查看的,後續的緩存中有數據的時候,經過緩存讀取
坑:
在使用SoringBoot整合shiro時候,使用的是Ehcache作緩存在shiro配置類中,配置了EhcacheManager,致使報錯,看了許多教程都是錯誤的,目前直接在 application文件中加載其配置類就行了,直接緩存信息