spring cache 应用Jcache和ehcache3.x 实践

来源:互联网 发布:阿里云怎么备案 编辑:程序博客网 时间:2024/06/04 19:34

Ehcache 3.x 默认实现了JCacheJSR-107,而sprin默认也支持JCache,所以不用额外的依赖或工作,就能工作良好(Ehcache 2.x 我们忽略不讲,spring也可以很方便的支持)。

 

这里以excache 3.x 为例:

 

① 首先需要引入ehcache依赖 以及 jcache-api

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

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

 

 

② 然后配置在 spring中配置ehcacheManager

 

下图是我 测试ehcache demo配置文件

 

<context:component-scan base-package="com.ly.examples.cache"/><cache:annotation-driven cache-manager="cacheManager"/><!--  spring cache with jdk map --><bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">    <property name="caches">        <set>            <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="default"/>            <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="product"/>        </set>    </property></bean>

 

③ 添加ehcache xml配置文件

下图是我测试的 demo 配置:

<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-3.0.xsd">
    <!-- 这个配置是ehcache 自己的配置 用来配置ehcache manager
       比如我们可以配置ehcache 实例
       -->

    <!-- 定义一个cache 实例配置 别名是 product
     key 的类型为 string
     最多允许2000 个 entries(可以理解为2000个key-value 对 )
     最多使用500m内存
     -->
    <cache alias="product">
        <!--<key-type>java.lang.String</key-type>-->
        <resources>
            <heap unit="entries">2000</heap>
            <offheap unit="MB">500</offheap>
        </resources>
    </cache>

    <!-- 定义一个cache模板 ,模板是抽象定义,可以被cache 实例配置继承  -->
    <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>

    <!-- 定义一个 default cache  使用 myDefaults 模板 这里 覆盖了模板的key-type 配置 -->
    <cache alias="default" uses-template="myDefaults">
        <key-type>java.lang.Object</key-type>
        <value-type>java.lang.Object</value-type>
    </cache>

</config>

④ 接下来 你就可以使用spring 缓存 注解或者 JCache 标准注解了。

1 0
原创粉丝点击