spring cache 应用Jcache和ehcache3.x 实践

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 标准注解了。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值