• Ehcache学习笔记(三) 与Spring集成


    Spring EhCache集成

    所需jar包

    Ehcache2.6.6  [ehcache-core-2.6.6.jar]  ,Spring3 M2(全部jar) ,slf4j-api-1.6.1.jar,slf4j-jdk14-1.6.1.jar

    先定义EhCache的配置文件:ehcache.xml  具体详细配置说明这里不做解释,关于ehcache的教程网上很多。

    <?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="true" monitoring="autodetect"
             dynamicConfig="true">
        <cache 
            name="sampleCache" 
            maxElementsInMemory="1000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            memoryStoreEvictionPolicy="LRU"
        >
        </cache>
    </ehcache>

    在Spring的XML当中配置与EhCache集成

    <?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:tx="http://www.springframework.org/schema/tx"
        xmlns:context="http://www.springframework.org/schema/context"  
        xmlns:mvc="http://www.springframework.org/schema/mvc"  
        xmlns:aop="http://www.springframework.org/schema/aop"
        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/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
       
        <cache:annotation-driven cache-manager="ehCacheCacheManager"/>
        
        <bean id="ehCacheManagerFactoryBean" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
            <property name="configLocation" value="WEB-INF/ehcache.xml"></property>
        </bean>
        
        <bean id="ehCacheCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" >
            <property name="cacheManager" ref="ehCacheManagerFactoryBean" />
        </bean>
    </beans>

    1、<cache:annotation-driven cache-manager="ehCacheCacheManager"/> 开启注解支持,这样可以使用Spring的注解来操作缓存。

    2、ehCacheManagerFactoryBean 用来初始化Ehcache的CacheManager

    3、ehCacheCacheManager 配置Spring的缓存管理器

    以上配置就完成了EhCache与Spring的集成

    Spring还提供了与其他缓存框架的支持,具体配置细节可以查看官方文档。

    如果Spring与多个缓存框架集成 可以配置CompositeCacheManager用于组合CacheManager,即可以从多个CacheManager中轮询得到相应的Cache。

    <bean id="cacheManager" class="org.springframework.cache.support.CompositeCacheManager">
        <property name="cacheManagers">
            <list>
                <ref bean="ehcacheManager"/>
                <ref bean="jcacheManager"/>
            </list>
        </property>
        <property name="fallbackToNoOpCache" value="true"/>
    </bean>

    当我们调用cacheManager.getCache(cacheName) 时,会先从第一个cacheManager中查找有没有cacheName的cache,如果没有接着查找第二个,如果最后找不到,因为fallbackToNoOpCache=true,那么将返回一个NOP的Cache否则返回null。

     

    一般我们使用Cache注解在Spring当中使用缓存。

    @Cacheable

    应用到读取数据的方法上,即可缓存的方法,如查找方法:先从缓存中读取,如果没有再调用方法获取数据,然后把数据添加到缓存中。

    (即从缓存中读取数据,同时也将数据放入缓存)

    public @interface Cacheable {
        String[] value();  //缓存的名字,可以把数据写到多个缓存  
        String key() default "";   //缓存key,如果不指定将使用默认的KeyGenerator生成,后边介绍  
        String condition() default ""; //满足缓存条件的数据才会放入缓存
    }

    @CachePut 

    用法类似于@Cacheable,但是用于存放数据声明(如更新数据),所以每次都会执行,将执行后的结果存入缓存。

    (只往缓存里放数据,不从缓存中读数据)

    public @interface CachePut {
        String[] value();
        String key() default "";
        String condition() default "";
    }

    @CacheEvict 

    即应用到移除数据的方法上,如删除方法,调用方法时会从缓存中移除相应的数据。

    (从缓存中清除数据)

    public @interface CacheEvict {  
        String[] value();                        //请参考@CachePut  
        String key() default "";                 //请参考@CachePut  
        String condition() default "";           //请参考@CachePut  
        boolean allEntries() default false;      //是否移除所有数据  
        boolean beforeInvocation() default false;//是调用方法之前移除/还是调用之后移除  
    }

    Spring 提供的SpEL上下文支持

    参考资料:http://jinnianshilongnian.iteye.com/blog/2001040?page=2 开涛

    1、缓存的key可以使用参数的属性 

    @Cacheable(value="books", key="#isbn")
    public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
    
    
    @Cacheable(value="books", key="#isbn.rawNumber")
    public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
    
    
    @Cacheable(value="books", key="T(someType).hash(#isbn)") // key="T(静态类的全名 包名+类名).方法(参数)"
    public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

    2、可以根据条件来决定是否使用缓存 condition表达式的条件满足才使用缓存。

    @Cacheable(value="book", condition="#name.length < 32")
    public Book findBook(String name)
    @Cacheable(value="UserMenuCache", key="#key", condition="#key.equals('ok')")
    public User userTokenCache(String key)
    @Cacheable(value = "user", key = "#id", condition = "#id lt 10")
    public User conditionFindById(final Long id)

    3、只往缓存中放数据

    @CachePut(value="UserMenuCache", key="#key")
    public User userTokenCache(String key)

    4、扩展key的生成,可以写一个静态代码,然后根据业务自定义key

     1 @Component
     2 public class SystemCacheManager {
     3     
     4     @CachePut(value="UserMenuCache", key="T(com.framework.code.component.SystemCacheManager).hashKey(#key)")
     5     public User userTokenCache(String key) {
     6         System.out.println("SystemCacheManager.userTokenCache()");
     7         User user = new User();
     8         user.setAge(18);
     9         return user;
    10     }
    11     
    12     public static String hashKey(String key) {
    13         System.out.println("SystemCacheManager.hashKey()");
    14         return "test" + key;
    15     }
    16 }

     

  • 相关阅读:
    re | frida | hook windows进程
    win32 | 透明窗口实现&画一个透明背景
    re | [SWPU2019]EasiestRe
    re | [QCTF2018]babyre
    web | [CISCN2019 总决赛 Day2 Web1]Easyweb
    sql | sqlite3的sqlite_master表探究
    windows | 获取系统变量ProgramData
    【友晶科技Terasic】Avalon-MM slave 为什么 readdata 要在第二个时钟周期才有数据?
    友晶科技 Terasic SOC FPGA的板子提供的image 使用了几个核? 是CPU0还是CPU1?
    【友晶科技Terasic】 用sopc-create-header-files工具生成 FPGA 硬件地址信息 用于与linux 程序交互 generate_hps_qsys_header.sh
  • 原文地址:https://www.cnblogs.com/daxin/p/3111453.html
Copyright © 2020-2023  润新知