现在Ehcache版本已经到3.10了, 网上查到的大部分还是2.x版本的使用说明, 把基础用法记了一下, 以后有时间再翻译.

基础使用, 创建 CacheManager

CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.withCache("preConfigured",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))
.build();
cacheManager.init(); Cache<Long, String> preConfigured =
cacheManager.getCache("preConfigured", Long.class, String.class); Cache<Long, String> myCache = cacheManager.createCache("myCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))); myCache.put(1L, "da one!");
String value = myCache.get(1L); cacheManager.removeCache("preConfigured"); cacheManager.close();
  1. The static method org.ehcache.config.builders.CacheManagerBuilder.newCacheManagerBuilder returns a new org.ehcache.config.builders.CacheManagerBuilder instance.
  2. Use the builder to define a Cache with alias "preConfigured". This cache will be created when cacheManager.build() is invoked on the actual CacheManager instance.
    • The first String argument is the cache alias, which is used to retrieve the cache from the CacheManager.
    • The second argument, org.ehcache.config.CacheConfiguration, is used to configure the Cache. We use the static newCacheConfigurationBuilder() method on org.ehcache.config.builders.CacheConfigurationBuilder to create a default configuration.
  3. Finally, invoking build() returns a fully instantiated, but uninitialized, CacheManager we can use.
  4. Before using the CacheManager it needs to be initialized, which can be done in 1 of 2 ways:
    • Calling CacheManager.init() on the CacheManager instance, or
    • Calling the CacheManagerBuilder.build(boolean init) method with the boolean parameter set to true.
  5. A cache is retrieved by passing its alias, key type and value type to the CacheManager. For instance, to obtain the cache declared in step 2 you need its alias="preConfigured",keyType=Long.class and valueType=String.class. For type-safety, we ask for both key and value types to be passed in. If these differ from the ones we expect, the CacheManager throws a ClassCastException early in the application’s lifecycle. This guards the Cache from being polluted by random types.
  6. The CacheManager can be used to create new Cache instances as needed. Just as in step 2, it requires passing in an alias as well as a CacheConfiguration. The instantiated and fully initialized Cache added will be returned and/or accessed through the CacheManager.getCache API.
  7. The newly added Cache can now be used to store entries, which are comprised of key value pairs. The put method’s first parameter is the key and the second parameter is the value. Remember the key and value types must be the same types as those defined in the CacheConfiguration. Additionally the key must be unique and is only associated with one value.
  8. A value is retrieved from a cache by calling the cache.get(key) method. It only takes one parameter which is the key, and returns the value associated with that key. If there is no value associated with that key then null is returned.
  9. We can CacheManager.removeCache(String) a given Cache. The CacheManager will not only remove its reference to the Cache, but will also close it. The Cache releases all locally held transient resources (such as memory). References to this Cache become unusable.
  10. In order to release all transient resources (memory, threads, …​) a CacheManager provides to Cache instances it manages, you have to invoke CacheManager.close(), which in turns closes all Cache instances known at the time.
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
// A default configuration can be provided at CacheManager level to be used by the caches unless defined explicitly.
.withDefaultSizeOfMaxObjectSize(500, MemoryUnit.B)
.withDefaultSizeOfMaxObjectGraph(2000)
.withCache("usesConfiguredInCache", usesConfiguredInCacheConfig)
.withCache("usesDefaultSizeOfEngine", usesDefaultSizeOfEngineConfig)
.build(true);

创建缓存

// Only 10 entries allowed on heap. Eviction will occur when full.
ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES);
// A shortcut to specify 10 entries.
ResourcePoolsBuilder.heap(10);
// Only 10 MB allowed. Eviction will occur when full.
ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, MemoryUnit.MB);

For every tier except the heap tier, calculating the size of the cache is fairly easy. You more or less sum the size of all byte buffers containing the serialized entries.

When heap is limited by size instead of entries, it is a bit more complicated. Byte sizing has a runtime performance impact that depends on the size and graph complexity of the data cached.

持久化缓存

PersistentCacheManager persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.with(CacheManagerBuilder.persistence(new File(getStoragePath(), "myData")))
.withCache("threeTieredCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
ResourcePoolsBuilder.newResourcePoolsBuilder()
.heap(10, EntryUnit.ENTRIES)
.offheap(1, MemoryUnit.MB)
.disk(20, MemoryUnit.MB, true)
)
).build(true); Cache<Long, String> threeTieredCache = persistentCacheManager.getCache("threeTieredCache", Long.class, String.class);
threeTieredCache.put(1L, "stillAvailableAfterRestart"); persistentCacheManager.close();
  1. If you wish to use disk storage (like for persistent Cache instances), you’ll have to provide a location where data should be stored on disk to the CacheManagerBuilder.persistence() static method.
  2. You define a resource pool for the heap. This will be your faster but smaller pool.
  3. You define a resource pool for the off-heap. Still pretty fast and a bit bigger.
  4. You define a persistent resource pool for the disk. It is persistent because said it should be (last parameter is true).
  5. All values stored in the cache will be available after a JVM restart (assuming the CacheManager has been closed cleanly by calling close())

缓存过期

CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
ResourcePoolsBuilder.heap(100))
.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(20)))
.build();
  1. Expiry is configured at the cache level, so start by defining a cache configuration,
  2. then add to it an Expiry, here using the predefined time-to-live one, configured with the required Duration

例子

public static void testOffHeapClientClass() {
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.withClassLoader(TestMethods.class.getClassLoader())
.withCache("myCache", newCacheConfigurationBuilder(Long.class, Order.class, newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).offheap(2, MemoryUnit.MB))
.build())
.build(true); Cache<Long, Order> cache = cacheManager.getCache("myCache", Long.class, Order.class); Order order = new Order(42L);
cache.put(42L, order); assertTrue(cache.get(42L) instanceof Order); cache.replace(42L, order, new Order(-1L)); assertEquals(-1L, cache.get(42L).id);
}

文档

Ehcache 3.x 笔记的更多相关文章

  1. ehcache的学习笔记(一)

    学习ehcache文档: 介绍:Ehcache是一个开源的项目,用来提高性能的基于标准化的缓存,无需使用数据库,简化了可扩展性.他是最广泛使用的基于java的缓存,因为他是强壮的,被证实的,功能全面的 ...

  2. Mybatis学习笔记汇总(包括源码和jar包)

    博客整理 Mybatis学习笔记(一)--对原生jdbc中问题的总结 Mybatis学习笔记(二)--Mybatis框架 Mybatis学习笔记(三)--入门程序 MyBatis学习笔记(四)--入门 ...

  3. Hibernate学习笔记之EHCache的配置

    Hibernate默认二级缓存是不启动的,启动二级缓存(以EHCache为例)需要以下步骤: 1.添加相关的包: Ehcache.jar和commons-logging.jar,如果hibernate ...

  4. ehcache 使用笔记

    要想使用 java 的本地缓存,可以考虑用 ehcache,或者 guava. guava 更高端一点,可以自动定时刷新.我选择了 ehcache. 在 spring 中是集成了 ehcache 的. ...

  5. 我的ehcache笔记

    我的EhcacheUtils类: package com.shinho.bi.utils; import org.ehcache.CacheManager; import org.ehcache.co ...

  6. SpringBoot整合EHcache学习笔记

    为了提高系统的运行效率,引入缓存机制,减少数据库访问和磁盘IO.下面说明一下ehcache和SpringBoot整合配置 前言介绍 EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特 ...

  7. MyBatis笔记——EhCache二级缓存

    介绍 ehcache是一个分布式缓存框架. 我们系统为了提高系统并发,性能.一般对系统进行分布式部署(集群部署方式)  不使用分布缓存,缓存的数据在各各服务单独存储,不方便系统开发.所以要使用分布式缓 ...

  8. SpringBoot学习笔记(10)-----SpringBoot中使用Redis/Mongodb和缓存Ehcache缓存和redis缓存

    1. 使用Redis 在使用redis之前,首先要保证安装或有redis的服务器,接下就是引入redis依赖. pom.xml文件如下 <dependency> <groupId&g ...

  9. [原创]java WEB学习笔记93:Hibernate学习之路---Hibernate 缓存介绍,缓存级别,使用二级缓存的情况,二级缓存的架构集合缓存,二级缓存的并发策略,实现步骤,集合缓存,查询缓存,时间戳缓存

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  10. EhCache 分布式缓存/缓存集群

    开发环境: System:Windows JavaEE Server:tomcat5.0.2.8.tomcat6 JavaSDK: jdk6+ IDE:eclipse.MyEclipse 6.6 开发 ...

随机推荐

  1. 【荐】开源Winform控件库:花木兰控件库

    微信好友推荐,挺好看的Winfrom控件库,下面来看看. 介绍 基于 C#(语言) 4.0 . VS2019 . Net Framework 4.0(不包括Net Framework 4.0 Clie ...

  2. 06-Shell内置命令

    1.内置命令介绍 Shell 内置命令,就是由 Bash Shell 自身提供的命令,而不是文件系统中的可执行文件. 使用type 来确定一个命令是否是内置命令: type 命令 通常来说,内置命令会 ...

  3. EasyNetQ(RabbitMQ)在处理消息时,如果抛出异常,继续不断发送到订阅队列,不断处理(也就是不自动确认消息已到达)

    默认情况下,EasyNetQ的消息处理过程中,如果throw exception,那么,依然是认为消息已经送达,不会再次推送,为了让RabbitMQ再次推送,可以这么实现: public sealed ...

  4. MyBatis——第一个程序

    MyBatis1:初识 MyBatis第一个程序 流程:搭建环境–>导入MyBatis–>编写代码–>测试 1.创建一张User表. 关键字id.username.pwd 2.导入相 ...

  5. 百度网盘(百度云)SVIP超级会员共享账号每日更新(2023.11.26)

    一.百度网盘SVIP超级会员共享账号 可能很多人不懂这个共享账号是什么意思,小编在这里给大家做一下解答. 我们多知道百度网盘很大的用处就是类似U盘,不同的人把文件上传到百度网盘,别人可以直接下载,避免 ...

  6. 凡是有但是-varchar和nvarchar的初步学习之一

    凡是有但是-varchar和nvarchar的初步学习之一 背景 高应用开发, 在涉及到国内国外的问题时,重要的事情有两个: 时区转换, 字符集转换. 时区转换虽然是很难理清楚, 各种规范不统一的事情 ...

  7. Harbor修改默认网段以及设置开机启动的方法

    Harbor修改默认网段以及设置开机启动的方法 背景 docker 默认的网段是 172.16.xx.xx 网段. harbor进行设置时会自动加1 设置为 172.17.xx.xx 有时候这个网段是 ...

  8. [转帖]浅谈RAID写惩罚(Write Penalty)与IOPS计算

    https://www.dell.com/community/%E6%95%B0%E6%8D%AE%E5%AD%98%E5%82%A8%E5%92%8C%E4%BF%9D%E6%8A%A4-%E8%B ...

  9. Python学习之十八_获取神通数据库所有的表数据量

    Python学习之十八_获取神通数据库所有的表数据量 背景 今天想获取一下所有数据库的表信息.但是发现神通数据库的系统表里面的表信息不正确 无法获取实际意义的表信息. 联系了下神通数据库的原厂高手. ...

  10. 小Min_25筛小记🐤

    这里的小Min_25筛,可以筛出 $10^11$ 以内所有质数的完全积性函数之和 注意事项: 1. cmd 的题解里面下标写得不清楚,应该是 $S'(p_k-1,k-1)$ 而不是 $S'(p_{k- ...