基本要素:版本、概念与抽象

  • Ehcache 3.x是一个用Java语言实现的缓存库,并且实现了 JSR107规范
  • Ehcache从2.x升级到3.x后,Maven依赖从 net.sf.ehcache:ehcache:2.x 变成了org.ehcache:ehcache:3.x
  • Ehcache基本概念有:
    • 要缓存的对象是“键值对”
    • 键值对的容器就是“缓存Cache”
    • 每个缓存有自己的配置,就是“缓存配置CacheConfiguration”,通过CacheConfigurationBuilder构建
    • Ehcache中可以管理多个缓存,需要一个“缓存管理器CacheManager”。通过CacheManager+缓存的名称可以创建或获得缓存
    • 缓存对象的存储位置有: 堆内存heap;堆外内存offheap;硬盘disk。 offheap就是位于JVM外的内存,不受GC管理

通过编程方式创建缓存

引入依赖

        <dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.8.0</version>
</dependency>

测试代码

    @Test
public void testA() {
CacheManagerBuilder builder = CacheManagerBuilder.newCacheManagerBuilder();
CacheManager cacheManager = builder.build();
cacheManager.init();//cacheManager创建后一定要初始化 ResourcePoolsBuilder poolsBuilder = ResourcePoolsBuilder.newResourcePoolsBuilder();
ResourcePools pools = poolsBuilder.heap(10, EntryUnit.ENTRIES).build();//用于配置一个cache的heap/offheap/disk的容量.
CacheConfigurationBuilder<Long, String> cacheConfigBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, pools);
CacheConfiguration<Long, String> cacheConfiguration = cacheConfigBuilder.build();//创建一个缓存配置 Cache myCache = cacheManager.createCache("myCache", cacheConfiguration);//根据缓存名称和缓存配置创建缓存
myCache.put(1L, "hahaha");
logger.info("{}", myCache.get(1L));
cacheManager.close();//系统关闭时, 应调用cacheManager的close方法
}

通过XML配置创建缓存

Ehcache的XML配置:

<?xml version="1.0" encoding="UTF-8" ?>
<config
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns='http://www.ehcache.org/v3'
xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd"> <!-- 可以把多个缓存配置相同的部分抽象出来形成cache-template模板 -->
<cache-template name="myDefaults">
<key-type>java.lang.Long</key-type>
<value-type>java.lang.String</value-type>
<heap unit="entries">200</heap>
</cache-template> <cache alias="foo">
<key-type>java.lang.String</key-type>
<value-type>java.lang.String</value-type>
<resources>
<heap unit="entries">20</heap> <!-- heap可以存储20个元素 -->
<offheap unit="MB">10</offheap> <!-- offheap可以存储10MB -->
</resources>
</cache> <!-- 继承cache-template模板 -->
<cache alias="bar" uses-template="myDefaults">
<key-type>java.lang.Number</key-type>
</cache> <cache alias="simpleCache" uses-template="myDefaults" /> </config>

测试代码:

    @Test
public void testB() {
URL ehcacheConfigUrl = getClass().getResource("/ehcache.xml");
Configuration configuration = new XmlConfiguration(ehcacheConfigUrl); //从XML配置改造缓存配置
CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);//创建CacheManager
cacheManager.init(); Cache<String, String> foo = cacheManager.getCache("foo", String.class, String.class);//从CachaManager用缓存名称获取缓存
foo.put("1", "hehehe");
logger.info("{}", foo.get("1")); Cache<Number, String> bar = cacheManager.getCache("bar", Number.class, String.class);
bar.put(1, "hohoho");
logger.info("{}", bar.get(1)); cacheManager.close(); }

通过JSR107(JCache)的api获取Ehcache的缓存--编程方式

    @Test
public void testA() { //CachingProvider provider = Caching.getCachingProvider("org.ehcache.jsr107.EhcacheCachingProvider");
CachingProvider provider = Caching.getCachingProvider();//通过spi技术找到provider. 适用于类路径中只有一个JCache实现, 否则得用上面一行代码指明provider
CacheManager cacheManager = provider.getCacheManager(); ResourcePoolsBuilder poolsBuilder = ResourcePoolsBuilder.newResourcePoolsBuilder();
ResourcePools pools = poolsBuilder.heap(10, EntryUnit.ENTRIES).build();
CacheConfigurationBuilder<Long, String> configBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, pools);
CacheConfiguration<Long, String> cacheConfig = configBuilder.build();//ehcache的configuration Cache<Long, String> cache = cacheManager.createCache("myCache", Eh107Configuration.fromEhcacheCacheConfiguration(cacheConfig));//通过Eh107Configuration将ehcache的config转为jcache的config
cache.put(1L, "hahaha");
logger.info("{}", cache.get(1L));
cacheManager.close(); }

通过JSR107(JCache)的api获取Ehcache的缓存--XML配置

引入JSR107规范

        <dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>1.1.1</version>
</dependency>

Ehcache的XML配置采用上面的

测试代码:

    @Test
public void testB() throws Exception { CachingProvider provider = Caching.getCachingProvider("org.ehcache.jsr107.EhcacheCachingProvider");
URI uri = getClass().getResource("/ehcache.xml").toURI();
CacheManager cacheManager = provider.getCacheManager(uri, getClass().getClassLoader());
Cache<String, String> cache = cacheManager.getCache("foo", String.class, String.class);
cache.put("1", "hehehe");
logger.info("{}", cache.get("1"));
cacheManager.close(); }

通过JCache在Spring中注入Ehcache

Spring的XML配置

    <bean id="jCacheManager" class="org.springframework.cache.jcache.JCacheManagerFactoryBean">
<property name="cacheManagerUri" value="classpath:ehcache.xml" />
</bean> <bean id="cacheManager" class="org.springframework.cache.jcache.JCacheCacheManager">
<property name="cacheManager" ref="jCacheManager" />
</bean>

测试代码:

@ContextConfiguration("classpath:spring.xml")
public class SpringJcacheEhcacheTest extends AbstractTestNGSpringContextTests { private static final Logger logger = LoggerFactory.getLogger(SpringJcacheEhcacheTest.class); @Autowired
private CacheManager cacheManager; @Test
public void testA() {
Cache<Number, String> barCache = cacheManager.getCache("bar", Number.class, String.class);
barCache.put(1, "hahaha");
barCache.put(2L, "hehehe");
logger.info("{}", barCache.get(1));
logger.info("{}", barCache.get(2L));
cacheManager.close();
} }

其他--在Spring中注入Ehcache 2.x

引入Ehcache2.x

        <dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.6</version>
</dependency>

Ehcache 2.x配置

<?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" monitoring="autodetect" dynamicConfig="true"> <diskStore path="java.io.tmpdir"/> <defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/> <cache name="foo"
eternal="false"
timeToLiveSeconds="300"
maxElementsInMemory="2000"
maxElementsOnDisk="20000"
overflowToDisk="true"
diskPersistent="true"
memoryStoreEvictionPolicy="FIFO"/> </ehcache>

spring的XML配置

    <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache-2.x.xml"/>
</bean> <bean id="cacheManager2.x" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="cacheManagerFactory"/>
</bean>

测试代码:

@ContextConfiguration("classpath:spring.xml")
public class SpringEhcache2xTest extends AbstractTestNGSpringContextTests { private static final Logger logger = LoggerFactory.getLogger(SpringEhcache2xTest.class); @Autowired
private EhCacheCacheManager ehCacheCacheManager; @Test
public void testA() {
CacheManager cacheManager = ehCacheCacheManager.getCacheManager();
Cache cache = cacheManager.getCache("foo");
Element ele = new Element(1L, "Ehcache 2.x");
cache.put(ele);
logger.info("{}", cache.get(1L).getObjectValue());
cacheManager.shutdown();
} }

最后

Ehcache 3.x官方文档: http://www.ehcache.org/documentation/3.8/getting-started.html

完整代码: https://github.com/JamboSonng/Demo-Master/tree/master/Master-Ehcache

0079 Ehcache 3.x应用入门及通过JCache与Spring整合的更多相关文章

  1. 项目一:第十四天 1.在realm中动态授权 2.Shiro整合ehcache 缓存realm中授权信息 3.动态展示菜单数据 4.Quartz定时任务调度框架—Spring整合javamail发送邮件 5.基于poi实现分区导出

    1 Shiro整合ehCache缓存授权信息 当需要进行权限校验时候:四种方式url拦截.注解.页面标签.代码级别,当需要验证权限会调用realm中的授权方法   Shiro框架内部整合好缓存管理器, ...

  2. Spring整合Ehcache管理缓存

    前言 Ehcache 是一个成熟的缓存框架,你可以直接使用它来管理你的缓存. Spring 提供了对缓存功能的抽象:即允许绑定不同的缓存解决方案(如Ehcache),但本身不直接提供缓存功能的实现.它 ...

  3. Spring整合Ehcache管理缓存(转)

    目录 前言 概述 安装 Ehcache的使用 HelloWorld范例 Ehcache基本操作 创建CacheManager 添加缓存 删除缓存 实现基本缓存操作 缓存配置 xml方式 API方式 S ...

  4. Ehcache和Spring整合

    Ehcache是使用Java编写的缓存框架,比较常用的是,整合在Hibernate和MyBatis这种关系型数据库持久框架. 不过现在用NoSQL也比较盛行,要应用Ehcache,整合起来就没法按照那 ...

  5. ehcache的基本使用及Spring整合

    1.ehcache:百度百科这样解释的,EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider.总的来说,他的出现就是减少对数据 ...

  6. Spring Boot入门教程1、使用Spring Boot构建第一个Web应用程序

    一.前言 什么是Spring Boot?Spring Boot就是一个让你使用Spring构建应用时减少配置的一个框架.约定优于配置,一定程度上提高了开发效率.https://zhuanlan.zhi ...

  7. Spring Boot入门教程2-1、使用Spring Boot+MyBatis访问数据库(CURD)注解版

    一.前言 什么是MyBatis?MyBatis是目前Java平台最为流行的ORM框架https://baike.baidu.com/item/MyBatis/2824918 本篇开发环境1.操作系统: ...

  8. Ehcache 3.7文档—基础篇—JCache aka JSR-107

    一. 概述JCache Java临时缓存API(JSR-107),也被称为JCache,它是一个规范在javax.cache.API中定义的.该规范是在Java Community Process下开 ...

  9. Spring整合EHCache框架

    在Spring中使用缓存可以有效地避免不断地获取相同数据,重复地访问数据库,导致程序性能恶化. 在Spring中已经定义了缓存的CacheManager和Cache接口,只需要实例化便可使用. Spr ...

随机推荐

  1. Mancala II

    题目描述 Mancala is a family of board games played around the world, sometimes called sowing games, or c ...

  2. 怎样获取Cookie

    使用 document.cookie 获取; document.cookie

  3. Jmeter4.0---- jmeter逻辑控制器(16)

    1.说明 逻辑控制器可以帮助用户控制Jmeter的测试逻辑,特别是何时发送请求.逻辑控制器可以改变其子测试元件的请求执行顺序. 2.逻辑控制器 (1)如果(if)控制器  用法一: 审核人员,数据分为 ...

  4. Entity的约束

    在DBContext的OnModelCreating()方法中调用上面的那个类 1.Infrastruture的Database文件夹建立Entityconfiguretions的文件夹 2.MyCo ...

  5. python+django学习四

    1.setting.py中设置好   STATIC_URL = '/static/'STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')] 前端文件存 ...

  6. lua堆栈

    lua堆栈 来源 https://blog.csdn.net/suhuaiqiang_janlay/article/details/56702381 来源 https://blog.csdn.net/ ...

  7. 微信小程序带参数生成二维码

    wx.request({ url: 'https://api.weixin.qq.com/cgi-bin/token', header: { 'content-type': 'application/ ...

  8. CHD-5.3.6集群上hive安装

    解压过后: [hadoop@master CDH5.3.6]$ ls -rlttotal 8drwxr-xr-x. 17 hadoop hadoop 4096 Jun  2 16:07 hadoop- ...

  9. 操作xml文件

    http://www.cnblogs.com/ 一.xml文件体系如下: <?xml version="1.0" encoding="utf-8" ?&g ...

  10. OpenCV_contrib里的Text(自然场景图像中的文本检测与识别)

    平台:win10 x64 +VS 2015专业版 +opencv-3.x.+CMake 待解决!!!Issue说明:最近做一些字符识别的事情,想试一下opencv_contrib里的Text(自然场景 ...