springboot 集成 ehcache3.x

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/woaiqianzhige/article/details/85303409

springboot 集成 ehcache3.x

上一篇是集成ehcache2.x的版本,ehcache3.x改动较大,实现jsr-107规范,所以需要进行修改

主要就是修改配置类和添加配置文件

maven

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

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

配置类

@Configuration
public class Conf {


@Bean
public CacheManager cacheManager() throws URISyntaxException, FileNotFoundException {
	*//*创建springCacheManager接口的具体实现类,参数是javax下面的CacheManager实现类*//*
	return new JCacheCacheManager(jCacheManager());
}

@Bean
public javax.cache.CacheManager jCacheManager() throws URISyntaxException, FileNotFoundException {

	//ehcache实现了javax的CachingProvider接口的具体实现
	EhcacheCachingProvider ehcacheCachingProvider = new EhcacheCachingProvider();

	//根据配置文件获取cachemanager
	URI uri = ResourceUtils.getURL("classpath:ehcache.xml").toURI();

	javax.cache.CacheManager cacheManager = ehcacheCachingProvider.getCacheManager(uri,this.getClass().getClassLoader());

	Cache<Long, OtcOrderDetail> orderDetailCache = cacheManager.getCache("orderDetailCache");


	return cacheManager;

}

}

配置文件

<config
    xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns='http://www.ehcache.org/v3'
    xmlns:jsr107='http://www.ehcache.org/v3/jsr107'
    xsi:schemaLocation="
    http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
    http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">

<!--为不同缓存配置不同配置模板-->

<cache alias="orderDetailCache" uses-template="orderDetailCache_template"/>
<cache alias="overrideCache" uses-template="overrideCache_template"/>

<cache-template name="orderDetailCache_template">
    <key-type>java.lang.Long</key-type>
    <value-type>com.fys.tradeim.message.OtcOrderDetail</value-type>
    <expiry>
        <ttl unit="hours">12</ttl>
    </expiry>
    <heap unit="entries">100000</heap>
    <jsr107:mbeans enable-statistics="true" enable-management="true"/>
</cache-template>


<cache-template name="overrideCache_template">
    <key-type>java.lang.String</key-type>
    <value-type>java.lang.String</value-type>
    <expiry>
        <ttl unit="minutes">2</ttl>
    </expiry>
    <heap>1</heap>
    <jsr107:mbeans enable-statistics="true" enable-management="true"/>
</cache-template>

<!--默认配置-->
<cache-template name="defaultCache">
    <heap>100</heap>
</cache-template>



</config>

主要是配置文件和配置方法变了,使用起来没有变化

查看命中率,缓存数量等信息

需要使用jdk提供的jconsole工具,具体百度一下,连接到我们的程序,选择项卡中找到 ‘mbean’的选项卡,点进去能看到 ‘statistics’和‘management’的配置信息
如何在代码中查看,我暂时还不知道

需要注意的

加上@Cacheable注解的方法A,如果被同类的方法B调用是不起作用的,两个解决办法

1.使用aspectj织入
2.将@Cacheable的方法单独提取到一个类中

推荐第二种

猜你喜欢

转载自blog.csdn.net/woaiqianzhige/article/details/85303409
今日推荐