1.Ehcahce是什么?
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。
Ehcache适用场景
1、比较少的更新数据表的情况
2、对并发要求不是很严格的情况
多台应用服务器中的缓存是不能进行实时同步的。
3、对一致性要求不高的情况下
因为Ehcache本地缓存的特性,目前无法很好的解决不同服务器间缓存同步的问题,所以我们在一致性要求非常高的场合下,尽量使用Redis、Memcached等集中式缓存。
2.Spring怎么集成ehcache
1、pom.xml
//除了SpringMVC 、sql server相关就是ehcache-core
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.11</version>
</dependency>
2.ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!-- 缓存到磁盘路径 -->
//java.io.tmpdir 默认的临时文件夹
<diskStore path="java.io.tmpdir" />
//默认配置
<defaultCache
maxElementsInMemory="10000" maxElementsOnDisk="0"
eternal="true" overflowToDisk="true"
diskPersistent="false" timeToIdleSeconds="0"
timeToLiveSeconds="0" diskSpoolBufferSizeMB="50"
diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LFU" />
//自定义配置
<cache name="myCache"
maxElementsInMemory="1000" maxElementsOnDisk="0"
eternal="false" overflowToDisk="false"
diskPersistent="false" timeToIdleSeconds="120"
timeToLiveSeconds="300" diskSpoolBufferSizeMB="50"
diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LFU" />
</ehcache>
关于缓存策略的理解:
memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。
- 1 FIFO,先进先出
- 2 LFU,最少被使用,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
- 3 LRU,(Ehcache默认策略),缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存
3.Spring配置,进行bean类的注入
<!--启用缓存注解-->
<cache:annotation-driven cache-manager="cacheManager"/>
<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml"/>
</bean>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="cacheManagerFactory"/>
</bean>
4.业务上应用
4.1 Service层里调用Dao层时使用缓存注解
在listAllUser方法上使用Cacheable注解,第一次运行时缓存里还没数据控制台会打印query from database...再次调用则直接读取缓存数据
@Cacheable(value = "myCache")
public List<User> listAllUser() {
System.out.println("query from database...");
return userDao.listAllUser();
}
4.2 Controller里调用
@Controller
@RequestMapping("/User")
public class UserController {
@Autowired
UserService userService;
@RequestMapping("/index")
public ModelAndView index(){
System.out.println("size:"+userService.listAllUser().size());
ModelAndView mav =new ModelAndView("index");
return mav;
}
}
3.Spring +ehcache +redis实现二级缓存
客官请移步
https://blog.csdn.net/liaoyulin0609/article/details/51787020
4.思考?
什么性质的数据适合放入缓存?
缓存池的大小怎么配置才能获得更好的性能?
ehcache一致性问题
ehcache是一种本地缓存,存放位置是JVM,所以它的一致性不好,并发写操作频繁的数据,不采用使用ehcache缓存;
读操作,先读缓存,缓存没有再去数据库读,并且把结果放到缓存中。