天天看点

ehcache +mybatis+spring 自定义缓存策略1       基于注解的支持2       配置Spring对Cache的支持3       键的生成策略4       Spring单独使用Ehcache

从3.1开始,spring引入了对cache的支持。其使用方法和原理都类似于spring对事务管理的支持。spring cache是作用在方法上的,其核心思想是这样的:当我们在调用一个缓存方法时会把该方法参数和返回结果作为一个键值对存放在缓存中,等到下次利用同样的参数来调用该方法时将不再执行该方法,而是直接从缓存中获取结果进行返回。所以在使用spring cache的时候我们要保证我们缓存的方法对于相同的方法参数要有相同的返回结果。

       使用spring cache需要我们做两方面的事:

n  声明某些方法使用缓存

n  配置spring对cache的支持

       和spring对事务管理的支持一样,spring对cache的支持也有基于注解和基于xml配置两种方式。下面我们先来看看基于注解的方式。

       spring为我们提供了几个注解来支持spring cache。其核心主要是@cacheable和@cacheevict。使用@cacheable标记的方法在执行后spring cache将缓存其返回结果,而使用@cacheevict标记的方法会在方法执行前或者执行后移除spring cache中的某些元素。下面我们将来详细介绍一下spring基于注解对cache的支持所提供的几个注解。

       @cacheable可以标记在一个方法上,也可以标记在一个类上。当标记在一个方法上时表示该方法是支持缓存的,当标记在一个类上时则表示该类所有的方法都是支持缓存的。对于一个支持缓存的方法,spring会在其被调用后将其返回值缓存起来,以保证下次利用同样的参数来执行该方法时可以直接从缓存中获取结果,而不需要再次执行该方法。spring在缓存方法的返回值时是以键值对进行缓存的,值就是方法的返回结果,至于键的话,spring又支持两种策略,默认策略和自定义策略,这个稍后会进行说明。需要注意的是当一个支持缓存的方法在对象内部被调用时是不会触发缓存功能的。@cacheable可以指定三个属性,value、key和condition。

       value属性是必须指定的,其表示当前方法的返回值是会被缓存在哪个cache上的,对应cache的名称。其可以是一个cache也可以是多个cache,当需要指定多个cache时其是一个数组。

   @cacheable("cache1")//cache是发生在cache1上的

   public user find(integer id) {

      returnnull;

   }

   @cacheable({"cache1", "cache2"})//cache是发生在cache1和cache2上的

       key属性是用来指定spring缓存方法的返回结果时对应的key的。该属性支持springel表达式。当我们没有指定该属性时,spring将使用默认策略生成key。我们这里先来看看自定义策略,至于默认策略会在后文单独介绍。

       自定义策略是指我们可以通过spring的el表达式来指定我们的key。这里的el表达式可以使用方法参数及它们对应的属性。使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”。下面是几个使用参数作为key的示例。

   @cacheable(value="users", key="#id")

   @cacheable(value="users", key="#p0")

   @cacheable(value="users", key="#user.id")

   public user find(user user) {

   @cacheable(value="users", key="#p0.id")

       除了上述使用方法参数作为key之外,spring还为我们提供了一个root对象可以用来生成key。通过该root对象我们可以获取到以下信息。

属性名称

描述

示例

methodname

当前方法名

#root.methodname

method

当前方法

#root.method.name

target

当前被调用的对象

#root.target

targetclass

当前被调用的对象的class

#root.targetclass

args

当前方法参数组成的数组

#root.args[0]

caches

当前被调用的方法使用的cache

#root.caches[0].name

       当我们要使用root对象的属性作为key时我们也可以将“#root”省略,因为spring默认使用的就是root对象的属性。如:

   @cacheable(value={"users", "xxx"}, key="caches[1].name")

       有的时候我们可能并不希望缓存一个方法所有的返回结果。通过condition属性可以实现这一功能。condition属性默认为空,表示将缓存所有的调用情形。其值是通过springel表达式来指定的,当为true时表示进行缓存处理;当为false时表示不进行缓存处理,即每次调用该方法时该方法都会执行一次。如下示例表示只有当user的id为偶数时才会进行缓存。

   @cacheable(value={"users"}, key="#user.id", condition="#user.id%2==0")

      system.out.println("find user by user " + user);

      return user;

       在支持spring cache的环境下,对于使用@cacheable标注的方法,spring在每次执行前都会检查cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则才会执行并将返回结果存入指定的缓存中。@cacheput也可以声明一个方法支持缓存功能。与@cacheable不同的是使用@cacheput标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。

       @cacheput也可以标注在类上和方法上。使用@cacheput时我们可以指定的属性跟@cacheable是一样的。

   @cacheput("users")//每次都会执行方法,并将结果存入指定的缓存中

       @cacheevict是用来标注在需要清除缓存元素的方法或类上的。当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作。@cacheevict可以指定的属性有value、key、condition、allentries和beforeinvocation。其中value、key和condition的语义与@cacheable对应的属性类似。即value表示清除操作是发生在哪些cache上的(对应cache的名称);key表示需要清除的是哪个key,如未指定则会使用默认策略生成的key;condition表示清除操作发生的条件。下面我们来介绍一下新出现的两个属性allentries和beforeinvocation。

       allentries是boolean类型,表示是否需要清除缓存中的所有元素。默认为false,表示不需要。当指定了allentries为true时,spring cache将忽略指定的key。有的时候我们需要cache一下清除所有的元素,这比一个一个清除元素更有效率。

   @cacheevict(value="users", allentries=true)

   public void delete(integer id) {

      system.out.println("delete user by id: " + id);

       清除操作默认是在对应方法成功执行之后触发的,即方法如果因为抛出异常而未能成功返回时也不会触发清除操作。使用beforeinvocation可以改变触发清除操作的时间,当我们指定该属性值为true时,spring会在调用该方法之前清除缓存中的指定元素。

   @cacheevict(value="users", beforeinvocation=true)

       其实除了使用@cacheevict清除缓存元素外,当我们使用ehcache作为实现时,我们也可以配置ehcache自身的驱除策略,其是通过ehcache的配置文件来指定的。由于ehcache不是本文描述的重点,这里就不多赘述了,想了解更多关于ehcache的信息,请查看我关于ehcache的专栏。

       @caching注解可以让我们在一个方法或者类上同时指定多个spring cache相关的注解。其拥有三个属性:cacheable、put和evict,分别用于指定@cacheable、@cacheput和@cacheevict。

   @caching(cacheable = @cacheable("users"), evict = { @cacheevict("cache2"),

         @cacheevict(value = "cache3", allentries = true) })

       spring允许我们在配置可缓存的方法时使用自定义的注解,前提是自定义的注解上必须使用对应的注解进行标注。如我们有如下这么一个使用@cacheable进行标注的自定义注解。

@target({elementtype.type, elementtype.method})

@retention(retentionpolicy.runtime)

@cacheable(value="users")

public @interface mycacheable {

}

       那么在我们需要缓存的方法上使用@mycacheable进行标注也可以达到同样的效果。

   @mycacheable

   public user findbyid(integer id) {

      system.out.println("find user by id: " + id);

      user user = new user();

      user.setid(id);

      user.setname("name" + id);

       配置spring对基于注解的cache的支持,首先我们需要在spring的配置文件中引入cache命名空间,其次通过<cache:annotation-driven />就可以启用spring对基于注解的cache的支持。

<?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.xsd">

   <cache:annotation-driven/>

</beans>

       <cache:annotation-driven/>有一个cache-manager属性用来指定当前所使用的cachemanager对应的bean的名称,默认是cachemanager,所以当我们的cachemanager的id为cachemanager时我们可以不指定该参数,否则就需要我们指定了。

       <cache:annotation-driven/>还可以指定一个mode属性,可选值有proxy和aspectj。默认是使用proxy。当mode为proxy时,只有缓存方法在外部被调用的时候spring

cache才会发生作用,这也就意味着如果一个缓存方法在其声明对象内部被调用时spring cache是不会发生作用的。而mode为aspectj时就不会有这种问题。另外使用proxy时,只有public方法上的@cacheable等标注才会起作用,如果需要非public方法上的方法也可以使用spring

cache时把mode设置为aspectj。

       此外,<cache:annotation-driven/>还可以指定一个proxy-target-class属性,表示是否要代理class,默认为false。我们前面提到的@cacheable、@cacheevict等也可以标注在接口上,这对于基于接口的代理来说是没有什么问题的,但是需要注意的是当我们设置proxy-target-class为true或者mode为aspectj时,是直接基于class进行操作的,定义在接口上的@cacheable等cache注解不会被识别到,那对应的spring

cache也不会起作用了。

       需要注意的是<cache:annotation-driven/>只会去寻找定义在同一个applicationcontext下的@cacheable等缓存注解。

       除了使用注解来声明对cache的支持外,spring还支持使用xml来声明对cache的支持。这主要是通过类似于aop:advice的cache:advice来进行的。在cache命名空间下定义了一个cache:advice元素用来定义一个对于cache的advice。其需要指定一个cache-manager属性,默认为cachemanager。cache:advice下面可以指定多个cache:caching元素,其有点类似于使用注解时的@caching注解。cache:caching元素下又可以指定cache:cacheable、cache:cache-put和cache:cache-evict元素,它们类似于使用注解时的@cacheable、@cacheput和@cacheevict。下面来看一个示例:

   <cache:advice id="cacheadvice" cache-manager="cachemanager">

      <cache:caching cache="users">

         <cache:cacheable method="findbyid" key="#p0"/>

         <cache:cacheable method="find" key="#user.id"/>

         <cache:cache-evict method="deleteall" all-entries="true"/>

      </cache:caching>

   </cache:advice>

       上面配置定义了一个名为cacheadvice的cache:advice,其中指定了将缓存findbyid方法和find方法到名为users的缓存中。这里的方法还可以使用通配符“*”,比如“find*”表示任何以“find”开始的方法。

       有了cache:advice之后,我们还需要引入aop命名空间,然后通过aop:config指定定义好的cacheadvice要应用在哪些pointcut上。如:

   <aop:config proxy-target-class="false">

      <aop:advisor advice-ref="cacheadvice" pointcut="execution(*

com.xxx.userservice.*(..))"/>

   </aop:config>

       上面的配置表示在调用com.xxx.userservice中任意公共方法时将使用cacheadvice对应的cache:advice来进行spring cache处理。更多关于spring aop的内容不在本文讨论范畴内。

       cachemanager是spring定义的一个用来管理cache的接口。spring自身已经为我们提供了两种cachemanager的实现,一种是基于java api的concurrentmap,另一种是基于第三方cache实现——ehcache,如果我们需要使用其它类型的缓存时,我们可以自己来实现spring的cachemanager接口或abstractcachemanager抽象类。下面分别来看看spring已经为我们实现好了的两种cachemanager的配置示例。

   <bean id="cachemanager" class="org.springframework.cache.support.simplecachemanager">

      <property name="caches">

         <set>

            <bean class="org.springframework.cache.concurrent.concurrentmapcachefactorybean" p:name="xxx"/>

         </set>

      </property>

   </bean>

       上面的配置使用的是一个simplecachemanager,其中包含一个名为“xxx”的concurrentmapcache。

   <!-- ehcache实现 -->

   <bean id="cachemanager" class="org.springframework.cache.ehcache.ehcachecachemanager" p:cache-manager-ref="ehcachemanager"/>

   <bean id="ehcachemanager" class="org.springframework.cache.ehcache.ehcachemanagerfactorybean" p:config-location="ehcache-spring.xml"/>

       上面的配置使用了一个spring提供的ehcachecachemanager来生成一个spring的cachemanager,其接收一个ehcache的cachemanager,因为真正用来存入缓存数据的还是ehcache。ehcache的cachemanager是通过spring提供的ehcachemanagerfactorybean来生成的,其可以通过指定ehcache的配置文件位置来生成一个ehcache的cachemanager。若未指定则将按照ehcache的默认规则取classpath根路径下的ehcache.xml文件,若该文件也不存在,则获取ehcache对应jar包中的ehcache-failsafe.xml文件作为配置文件。更多关于ehcache的内容这里就不多说了,它不属于本文讨论的内容,欲了解更多关于ehcache的内容可以参考我之前发布的ehcache系列文章,也可以参考官方文档等。

       键的生成策略有两种,一种是默认策略,一种是自定义策略。

       默认的key生成策略是通过keygenerator生成的,其默认策略如下:

n  如果方法没有参数,则使用0作为key。

n  如果只有一个参数的话则使用该参数作为key。

n  如果参数多余一个的话则使用所有参数的hashcode作为key。

       如果我们需要指定自己的默认策略的话,那么我们可以实现自己的keygenerator,然后指定我们的spring cache使用的keygenerator为我们自己定义的keygenerator。

       使用基于注解的配置时是通过cache:annotation-driven指定的.

   <cache:annotation-driven key-generator="userkeygenerator"/>

   <bean id="userkeygenerator" class="com.xxx.cache.userkeygenerator"/>

       而使用基于xml配置时是通过cache:advice来指定的。

   <cache:advice id="cacheadvice" cache-manager="cachemanager" key-generator="userkeygenerator">

       需要注意的是此时我们所有的cache使用的key的默认生成策略都是同一个keygenerator。

       前面介绍的内容是spring内置的对cache的支持,其实我们也可以通过spring自己单独的使用ehcache的cachemanager或ehcache对象。通过在application context中配置ehcachemanagerfactorybean和ehcachefactorybean,我们就可以把对应的ehcache的cachemanager和ehcache对象注入到其它的spring bean对象中进行使用。

     ehcachemanagerfactorybean是spring内置的一个可以产生ehcache的cachemanager对象的factorybean。其可以通过属性configlocation指定用于创建cachemanager的ehcache配置文件的路径,通常是ehcache.xml文件的路径。如果没有指定configlocation,则将使用默认位置的配置文件创建cachemanager,这是属于ehcache自身的逻辑,即如果在classpath根路径下存在ehcache.xml文件,则直接使用该文件作为ehcache的配置文件,否则将使用ehcache-xxx.jar中的ehcache-failsafe.xml文件作为配置文件来创建ehcache的cachemanager。此外,如果不希望创建的cachemanager使用默认的名称(在ehcache.xml文件中定义的,或者是由cachemanager内部定义的),则可以通过cachemanagername属性进行指定。下面是一个配置ehcachemanagerfactorybean的示例。

   <!-- 定义cachemanager -->

   <bean id="cachemanager" class="org.springframework.cache.ehcache.ehcachemanagerfactorybean">

      <!-- 指定配置文件的位置 -->

      <property name="configlocation" value="/web-inf/config/ehcache.xml"/>

      <!-- 指定新建的cachemanager的名称 -->

      <property name="cachemanagername" value="cachemanagername"/>

       ehcachefactorybean是用来产生ehcache的ehcache对象的factorybean。定义ehcachefactorybean时有两个很重要的属性我们可以来指定。一个是cachemanager属性,其可以指定将用来获取或创建ehcache的cachemanager对象,若未指定则将通过cachemanager.create()获取或创建默认的cachemanager。另一个重要属性是cachename,其表示当前ehcachefactorybean对应的是cachemanager中的哪一个ehcache对象,若未指定默认使用beanname作为cachename。若cachemanager中不存在对应cachename的ehcache对象,则将使用cachemanager创建一个名为cachename的cache对象。此外我们还可以通过ehcachefactorybean的timetoidle、timetolive等属性指定要创建的cache的对应属性,注意这些属性只对cachemanager中不存在对应cache时新建的cache才起作用,对已经存在的cache将不起作用,更多属性设置请参考spring的api文档。此外还有几个属性是对不管是已经存在还是新创建的cache都起作用的属性:statisticsenabled、sampledstatisticsenabled、disabled、blocking和cacheeventlisteners,其中前四个默认都是false,最后一个表示为当前cache指定cacheeventlistener。下面是一个定义ehcachefactorybean的示例。

   <!-- 定义一个ehcache -->

   <bean id="usercache" class="org.springframework.cache.ehcache.ehcachefactorybean">

      <property name="cachename" value="user"/>

      <property name="cachemanager" ref="cachemanager"/>

(注:本文是基于spring3.1.0所写)