当前位置: 移动技术网 > IT编程>开发语言>Java > 详解Spring整合Ehcache管理缓存

详解Spring整合Ehcache管理缓存

2019年07月22日  | 移动技术网IT编程  | 我要评论

前言

ehcache 是一个成熟的缓存框架,你可以直接使用它来管理你的缓存。

spring 提供了对缓存功能的抽象:即允许绑定不同的缓存解决方案(如ehcache),但本身不直接提供缓存功能的实现。它支持注解方式使用缓存,非常方便。

 本文先通过ehcache独立应用的范例来介绍它的基本使用方法,然后再介绍与spring整合的方法。

概述

ehcache是什么?

ehcache 是一个纯java的进程内缓存框架,具有快速、精干等特点。它是hibernate中的默认缓存框架。

ehcache已经发布了3.1版本。但是本文的讲解基于2.10.2版本。

为什么不使用最新版呢?因为spring4还不能直接整合ehcache 3.x。虽然可以通过jcache间接整合,ehcache也支持jcache,但是个人觉得不是很方便。

安装

ehcache

如果你的项目使用maven管理,添加以下依赖到你的pom.xml中。

<dependency>
 <groupid>net.sf.ehcache</groupid>
 <artifactid>ehcache</artifactid>
 <version>2.10.2</version>
 <type>pom</type>
</dependency>

如果你的项目不使用maven管理,请在 ehcache官网下载地址 下载jar包。

spring

如果你的项目使用maven管理,添加以下依赖到你的pom.xml中。

spring-context-support这个jar包中含有spring对于缓存功能的抽象封装接口。

<dependency>
 <groupid>org.springframework</groupid>
 <artifactid>spring-context-support</artifactid>
 <version>4.1.4.release</version>
</dependency>

ehcache的使用

helloworld范例

接触一种技术最快最直接的途径总是一个hello world例子,毕竟动手实践印象更深刻,不是吗?

(1) 在classpath下添加ehcache.xml

添加一个名为helloworld的缓存。

<?xml version="1.0" encoding="utf-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
   xsi:nonamespaceschemalocation="http://ehcache.org/ehcache.xsd">

 <!-- 磁盘缓存位置 -->
 <diskstore path="java.io.tmpdir/ehcache"/>

 <!-- 默认缓存 -->
 <defaultcache
   maxentrieslocalheap="10000"
   eternal="false"
   timetoidleseconds="120"
   timetoliveseconds="120"
   maxentrieslocaldisk="10000000"
   diskexpirythreadintervalseconds="120"
   memorystoreevictionpolicy="lru"/>

 <!-- helloworld缓存 -->
 <cache name="helloworld"
   maxelementsinmemory="1000"
   eternal="false"
   timetoidleseconds="5"
   timetoliveseconds="5"
   overflowtodisk="false"
   memorystoreevictionpolicy="lru"/>
</ehcache>

(2) ehcachedemo.java

 ehcache会自动加载classpath根目录下名为ehcache.xml文件。

ehcachedemo的工作步骤如下:

 在ehcachedemo中,我们引用ehcache.xml声明的名为helloworld的缓存来创建cache对象;

 然后我们用一个键值对来实例化element对象;

element对象添加到cache

 然后用cache的get方法获取element对象。

public class ehcachedemo {
 public static void main(string[] args) throws exception {
  // create a cache manager
  final cachemanager cachemanager = new cachemanager();

  // create the cache called "helloworld"
  final cache cache = cachemanager.getcache("helloworld");

  // create a key to map the data to
  final string key = "greeting";

  // create a data element
  final element putgreeting = new element(key, "hello, world!");

  // put the element into the data store
  cache.put(putgreeting);

  // retrieve the data element
  final element getgreeting = cache.get(key);

  // print the value
  system.out.println(getgreeting.getobjectvalue());
 }
}

输出

hello, world!

ehcache基本操作

elementcachecachemanager是ehcache最重要的api。

  1. element:缓存的元素,它维护着一个键值对。
  2. cache:它是ehcache的核心类,它有多个element,并被cachemanager管理。它实现了对缓存的逻辑行为。
  3. cachemanager:cache的容器对象,并管理着cache的生命周期。

创建cachemanager

下面的代码列举了创建cachemanager的五种方式。

 使用静态方法create()会以默认配置来创建单例的cachemanager实例。

newinstance()方法是一个工厂方法,以默认配置创建一个新的cachemanager实例。

此外,newinstance()还有几个重载函数,分别可以通过传入stringurlinputstream参数来加载配置文件,然后创建cachemanager实例。

// 使用ehcache默认配置获取单例的cachemanager实例
cachemanager.create();
string[] cachenames = cachemanager.getinstance().getcachenames();

// 使用ehcache默认配置新建一个cachemanager实例
cachemanager.newinstance();
string[] cachenames = manager.getcachenames();

// 使用不同的配置文件分别创建一个cachemanager实例
cachemanager manager1 = cachemanager.newinstance("src/config/ehcache1.xml");
cachemanager manager2 = cachemanager.newinstance("src/config/ehcache2.xml");
string[] cachenamesformanager1 = manager1.getcachenames();
string[] cachenamesformanager2 = manager2.getcachenames();

// 基于classpath下的配置文件创建cachemanager实例
url url = getclass().getresource("/anotherconfigurationname.xml");
cachemanager manager = cachemanager.newinstance(url);

// 基于文件流得到配置文件,并创建cachemanager实例
inputstream fis = new fileinputstream(new file
("src/config/ehcache.xml").getabsolutepath());
try {
 cachemanager manager = cachemanager.newinstance(fis);
} finally {
 fis.close();
}

添加缓存

需要强调一点,cache对象在用addcache方法添加到cachemanager之前,是无效的。

使用cachemanager的addcache方法可以根据缓存名将ehcache.xml中声明的cache添加到容器中;它也可以直接将cache对象添加到缓存容器中。

cache有多个构造函数,提供了不同方式去加载缓存的配置参数。

 有时候,你可能需要使用api来动态的添加缓存,下面的例子就提供了这样的范例。

// 除了可以使用xml文件中配置的缓存,你也可以使用api动态增删缓存
// 添加缓存
manager.addcache(cachename);

// 使用默认配置添加缓存
cachemanager singletonmanager = cachemanager.create();
singletonmanager.addcache("testcache");
cache test = singletonmanager.getcache("testcache");

// 使用自定义配置添加缓存,注意缓存未添加进cachemanager之前并不可用
cachemanager singletonmanager = cachemanager.create();
cache memoryonlycache = new cache("testcache", 5000, false, false, 5, 2);
singletonmanager.addcache(memoryonlycache);
cache test = singletonmanager.getcache("testcache");

// 使用特定的配置添加缓存
cachemanager manager = cachemanager.create();
cache testcache = new cache(
 new cacheconfiguration("testcache", maxentrieslocalheap)
 .memorystoreevictionpolicy(memorystoreevictionpolicy.lfu)
 .eternal(false)
 .timetoliveseconds(60)
 .timetoidleseconds(30)
 .diskexpirythreadintervalseconds(0)
 .persistence(new persistenceconfiguration().strategy(strategy.localtempswap)));
 manager.addcache(testcache);

删除缓存

删除缓存比较简单,你只需要将指定的缓存名传入removecache方法即可。

cachemanager singletonmanager = cachemanager.create();
singletonmanager.removecache("samplecache1");

实现基本缓存操作

cache最重要的两个方法就是put和get,分别用来添加element和获取element。

cache还提供了一系列的get、set方法来设置或获取缓存参数,这里不一一列举,更多api操作可参考官方api开发手册。

/**
 * 测试:使用默认配置或使用指定配置来创建cachemanager
 *
 * @author victor zhang
 */
public class cacheoperationtest {
 private final logger log = loggerfactory.getlogger(cacheoperationtest.class);

 /**
  * 使用ehcache默认配置(classpath下的ehcache.xml)获取单例的cachemanager实例
  */
 @test
 public void operation() {
  cachemanager manager = cachemanager.newinstance("src/test/resources/ehcache/ehcache.xml");

  // 获得cache的引用
  cache cache = manager.getcache("usercache");

  // 将一个element添加到cache
  cache.put(new element("key1", "value1"));

  // 获取element,element类支持序列化,所以下面两种方法都可以用
  element element1 = cache.get("key1");
  // 获取非序列化的值
  log.debug("key:{}, value:{}", element1.getobjectkey(), element1.getobjectvalue());
  // 获取序列化的值
  log.debug("key:{}, value:{}", element1.getkey(), element1.getvalue());

  // 更新cache中的element
  cache.put(new element("key1", "value2"));
  element element2 = cache.get("key1");
  log.debug("key:{}, value:{}", element2.getobjectkey(), element2.getobjectvalue());

  // 获取cache的元素数
  log.debug("cache size:{}", cache.getsize());

  // 获取memorystore的元素数
  log.debug("memorystoresize:{}", cache.getmemorystoresize());

  // 获取diskstore的元素数
  log.debug("diskstoresize:{}", cache.getdiskstoresize());

  // 移除element
  cache.remove("key1");
  log.debug("cache size:{}", cache.getsize());

  // 关闭当前cachemanager对象
  manager.shutdown();

  // 关闭cachemanager单例实例
  cachemanager.getinstance().shutdown();
 }
}

缓存配置

ehcache支持通过xml文件和api两种方式进行配置。

xml方式

ehcache的cachemanager构造函数或工厂方法被调用时,会默认加载classpath下名为ehcache.xml的配置文件。如果加载失败,会加载ehcache jar包中的ehcache-failsafe.xml文件,这个文件中含有简单的默认配置。

ehcache.xml配置参数说明:

  1. name:缓存名称。
  2. maxelementsinmemory:缓存最大个数。
  3. eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。
  4. timetoidleseconds:置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
  5. timetoliveseconds:缓存数据的生存时间(ttl),也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。
  6. maxentrieslocaldisk:当内存中对象数量达到maxelementsinmemory时,ehcache将会对象写到磁盘中。
  7. overflowtodisk:内存不足时,是否启用磁盘缓存。
  8. diskspoolbuffersizemb:这个参数设置diskstore(磁盘缓存)的缓存区大小。默认是30mb。每个cache都应该有自己的一个缓冲区。
  9. maxelementsondisk:硬盘最大缓存个数。
  10. diskpersistent:是否在vm重启时存储硬盘的缓存数据。默认值是false。
  11. diskexpirythreadintervalseconds:磁盘失效线程运行时间间隔,默认是120秒。
  12. memorystoreevictionpolicy:当达到maxelementsinmemory限制时,ehcache将会根据指定的策略去清理内存。默认策略是lru(最近最少使用)。你可以设置为fifo(先进先出)或是lfu(较少使用)。
  13. clearonflush:内存数量最大时是否清除。

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">

 <!-- 磁盘缓存位置 -->
 <diskstore path="java.io.tmpdir/ehcache"/>

 <!-- 默认缓存 -->
 <defaultcache
   maxentrieslocalheap="10000"
   eternal="false"
   timetoidleseconds="120"
   timetoliveseconds="120"
   maxentrieslocaldisk="10000000"
   diskexpirythreadintervalseconds="120"
   memorystoreevictionpolicy="lru">
 <persistence strategy="localtempswap"/>
 </defaultcache>

 <cache name="usercache"
   maxelementsinmemory="1000"
   eternal="false"
   timetoidleseconds="3"
   timetoliveseconds="3"
   maxentrieslocaldisk="10000000"
   overflowtodisk="false"
   memorystoreevictionpolicy="lru"/>
</ehcache>

api方式

xml配置的参数也可以直接通过编程方式来动态的进行配置(dynamicconfig没有设为false)。

cache cache = manager.getcache("samplecache"); 
cacheconfiguration config = cache.getcacheconfiguration(); 
config.settimetoidleseconds(60); 
config.settimetoliveseconds(120); 
config.setmaxentrieslocalheap(10000); 
config.setmaxentrieslocaldisk(1000000);

也可以通过disabledynamicfeatures()方式关闭动态配置开关。配置以后你将无法再以编程方式配置参数。

cache cache = manager.getcache("samplecache"); 
cache.disabledynamicfeatures();

spring整合ehcache

spring3.1开始添加了对缓存的支持。和事务功能的支持方式类似,缓存抽象允许底层使用不同的缓存解决方案来进行整合。
spring4.1开始支持jsr-107注解。

注:我本人使用的spring版本为4.1.4.release,目前spring版本仅支持ehcache2.5以上版本,但不支持ehcache3。

绑定ehcache

org.springframework.cache.ehcache.ehcachemanagerfactorybean这个类的作用是加载ehcache配置文件。

org.springframework.cache.ehcache.ehcachecachemanager这个类的作用是支持net.sf.ehcache.cachemanager。

spring-ehcache.xml的配置

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
  xmlns:cache="http://www.springframework.org/schema/cache"
  xsi:schemalocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/cache
  http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">

 <description>ehcache缓存配置管理文件</description>

 <bean id="ehcache" class="org.springframework.cache.ehcache.ehcachemanagerfactorybean">
 <property name="configlocation" value="classpath:ehcache/ehcache.xml"/>
 </bean>

 <bean id="cachemanager" class="org.springframework.cache.ehcache.ehcachecachemanager">
 <property name="cachemanager" ref="ehcache"/>
 </bean>

 <!-- 启用缓存注解开关 -->
 <cache:annotation-driven cache-manager="cachemanager"/>
</beans>

使用spring的缓存注解

开启注解

spring为缓存功能提供了注解功能,但是你必须启动注解。

 你有两个选择:

(1) 在xml中声明

像上一节spring-ehcache.xml中的做法一样,使用<cache:annotation-driven/>

<cache:annotation-driven cache-manager="cachemanager"/>

(2) 使用标记注解

 你也可以通过对一个类进行注解修饰的方式在这个类中使用缓存注解。

 范例如下:

@configuration
@enablecaching
public class appconfig {
}

注解基本使用方法

spring对缓存的支持类似于对事务的支持。

首先使用注解标记方法,相当于定义了切点,然后使用aop技术在这个方法的调用前、调用后获取方法的入参和返回值,进而实现了缓存的逻辑。

下面三个注解都是方法级别:

@cacheable

表明所修饰的方法是可以缓存的:当第一次调用这个方法时,它的结果会被缓存下来,在缓存的有效时间内,以后访问这个方法都直接返回缓存结果,不再执行方法中的代码段。

这个注解可以用condition属性来设置条件,如果不满足条件,就不使用缓存能力,直接执行方法。

可以使用key属性来指定key的生成规则。

@cacheput

@cacheable不同,@cacheput不仅会缓存方法的结果,还会执行方法的代码段。

它支持的属性和用法都与@cacheable一致。

@cacheevict

@cacheable功能相反,@cacheevict表明所修饰的方法是用来删除失效或无用的缓存数据。

下面是@cacheable、@cacheevict@cacheput基本使用方法的一个集中展示:

@service
public class userservice {
 // @cacheable可以设置多个缓存,形式如:@cacheable({"books", "isbns"})
 @cacheable({"users"})
 public user finduser(user user) {
  return finduserindb(user.getid());
 }

 @cacheable(value = "users", condition = "#user.getid() <= 2")
 public user finduserinlimit(user user) {
  return finduserindb(user.getid());
 }

 @cacheput(value = "users", key = "#user.getid()")
 public void updateuser(user user) {
  updateuserindb(user);
 }

 @cacheevict(value = "users")
 public void removeuser(user user) {
  removeuserindb(user.getid());
 }

 @cacheevict(value = "users", allentries = true)
 public void clear() {
  removeallindb();
 }
}

@caching

如果需要使用同一个缓存注解(@cacheable、@cacheevict或@cacheput)多次修饰一个方法,就需要用到@caching

@caching(evict = { @cacheevict("primary"), @cacheevict(cachenames="secondary", key="#p0") })
public book importbooks(string deposit, date date)

@cacheconfig

与前面的缓存注解不同,这是一个类级别的注解。

如果类的所有操作都是缓存操作,你可以使用@cacheconfig来指定类,省去一些配置。

@cacheconfig("books")
public class bookrepositoryimpl implements bookrepository {
 @cacheable
 public book findbook(isbn isbn) {...}
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网