缓存进行曲之本地缓存框架
本地缓存
数据类型:业务无关的小数据缓存。
常见框架:EhCache 纯Java开源缓存框架
优点:Ehcache提供了对大数据的内存和硬盘的存储,最近版本允许多实例、保存对象高灵活性、提供LRU、LFU、FIFO淘汰算法,基础属性支持热配置、支持的插件多。缓存管理器监听器 (CacheManagerListener)和 缓存监听器(CacheEvenListener),做一些统计或数据一致性广播挺好用的
缺点:功能强大的同时,也使其更加复杂。
EhCahce的核心类:
A、CacheManager:Cache的管理类;
B、Cache:具体的cache类信息,负责缓存的get和put等操作
C、CacheConfiguration :cache的配置信息,包含策略、最大值等信息
D、Element:cache中单条缓存数据的单位
CacheManager manager = CacheManager.newInstance("src/config/ehcache.xml"); manager.addCache("testCache"); Cache test = singletonManager.getCache("testCache"); test.put(new Element("key1", "value1")); manager.shutdown();
Cache testCache = new Cache( new CacheConfiguration("testCache", maxElements) .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU) .overflowToDisk(true) .eternal(false) .timeToLiveSeconds(60) .timeToIdleSeconds(30) .diskPersistent(false) .diskExpiryThreadIntervalSeconds(0));
Ehcache cache = cacheManager.getEhcache("xaCache"); transactionManager.begin();//开启事务 try { Element e = cache.get(key); Object result = complexService.doStuff(element.getValue()); cache.put(new Element(key, result)); complexService.doMoreStuff(result); transactionManager.commit(); } catch (Exception e) { transactionManager.rollback(); }
常见框架:guava Google提供的java工具类 很猛
Guava Cache是一个全内存的本地缓存实现,而且提供了线程安全机制,所以特别适合于代码中已经预料到某些值会被多次调用的场景。
获取当前缓存的总数量,自减一,删除并更新总数赋值到count
<dependencies> <!-- Spring boot Cache--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!--for guava cache--> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>27.0.1-jre</version> </dependency> </dependencies>
引入 Guava Cache的配置文件 GuavaCacheConfig
@Configuration @EnableCaching public class GuavaCacheConfig { @Bean public CacheManager cacheManager() { GuavaCacheManager cacheManager = new GuavaCacheManager(); cacheManager.setCacheBuilder( CacheBuilder.newBuilder(). expireAfterWrite(10, TimeUnit.SECONDS).//缓存存活时间为 10 秒,缓存最大数目为 1000 个 maximumSize(1000)); return cacheManager; } }
常用注解:
@Cacheable
:配置在getUsersByName
方法上表示其返回值将被加入缓存。同时在查询时,会先从缓存中获取,若不存在才再发起对数据库的访问@CachePut
:配置于方法上时,能够根据参数定义条件来进行缓存,其与@Cacheable
不同的是使用@CachePut
标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中,所以主要用于数据新增和修改操作上@CacheEvict
:配置于方法上时,表示从缓存中移除相应数据。
测试日志:
常见框架:guava Google提供的java工具类 最猛
Caffeine是使用Java8对Guava缓存的重写版本,在Spring 5.0或者Spring Boot 2.0中将取代,基于LRU算法实现,支持多种缓存过期策略。
推荐个人认为不错的文章
https://www.jianshu.com/p/9a80c662dac4
https://juejin.im/post/5b7593496fb9a009b62904fa
posted on 2019-03-26 17:27 湖人总冠军forever 阅读(228) 评论(0) 编辑 收藏 举报