php企业公司网站源码,wordpress推送,岳阳网站制作公司,网络关键词排名软件本地进程缓存特点 缓存在日常开发中起着至关重要的作用, 由于存储在内存中, 数据的读取速度非常快,能大量减少对数据库的访问,减少数据库的压力. 缓存分为两类:
分布式缓存, 例如Redis: 优点: 存储容量大, 可靠性更好, 可以在集群间共享缺点: 访问缓存存在网络开销场景: 缓存数…本地进程缓存特点 缓存在日常开发中起着至关重要的作用, 由于存储在内存中, 数据的读取速度非常快,能大量减少对数据库的访问,减少数据库的压力. 缓存分为两类:
分布式缓存, 例如Redis: 优点: 存储容量大, 可靠性更好, 可以在集群间共享缺点: 访问缓存存在网络开销场景: 缓存数据量较大, 可靠性要求较高, 需要在集群间共享 进程本地缓存, 例如HashMap, GuavaCache: 优点: 读取本地内存, 没有网络开销, 速度更快缺点: 存储容量有限, 可靠性较低, 无法共享场景: 性能要求较高, 缓存数据量较小
github: https://github.com/ben-manes/caffeine
引入依赖 dependencygroupIdcom.github.ben-manes.caffeine/groupIdartifactIdcaffeine/artifactId/dependency入门案例 Testvoid name() {CacheString, String cache Caffeine.newBuilder().build();String before cache.getIfPresent(gf);cache.get(gf, key - { return zhangmengdie; });String after cache.getIfPresent(gf);System.out.println(before before);System.out.println(after after);}输出结果: cache.get(gf, key - { return zhangmengdie; });会先去缓存里面查,没有查到,会执行后面的Function, 然后自动添加到缓存里
缓存驱逐策略 基于容量: 设置缓存的数量上限
CacheString, String cache Caffeine.newBuilder().maximumSize(100).build();基于时间: 设置缓存的有效时间
CacheString, String cache Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(10L)).build();基于引用: 设置缓存为软引用或弱引用, 利用GC来回收缓存数据 (性能较差,不建议使用)
总结: 在默认情况下,当一个缓存元素过期的时候, Caffeine不会立即将其清理和驱逐. 而是在一次读或写操作后, 或者在空闲时间完成对失效数据的驱逐 Testvoid name() throws InterruptedException {CacheString, String cache Caffeine.newBuilder().maximumSize(1L).build();cache.put(memo1, zhangmengdie);cache.put(memo2, jiacaimin);String memo1Before cache.getIfPresent(memo1);String memo2Before cache.getIfPresent(memo2);System.out.println(memo1Before memo1Before);System.out.println(memo2Before memo2Before);Thread.sleep(10L);String memo1After cache.getIfPresent(memo1);String memo2After cache.getIfPresent(memo2);System.out.println(memo1After memo1After);System.out.println(memo2After memo2After);}输出结果: 可以看到设置大小为1, 第一次取到了失效的数据, 休眠10ms后,取到为空,可见不是立即清除
example Configuration
public class CaffeienConfig {Beanpublic CacheLong, Person personCache(){return Caffeine.newBuilder().initialCapacity(100).maximumSize(10_000L).build();}}RestController
public class PersonController {Autowiredprivate PersonService personService;Autowiredprivate CacheLong, Person personCache;GetMapping(/{id})public Person queryById(PathVariable(id) Long id){return personCache.get(id, key - personService.query(key));}}