轻量级的缓存框架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文件中加载其配置类就行了,直接缓存信息