您的位置:首页 > 编程语言 > Java开发

SpringBoot框架结合EhCache缓存

2019-04-26 15:03 337 查看

1、首先pom文件需要增加依赖,spring包和cache包

<!-- 缓存依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>

2、创建ehcache.xml文件,并配置

<?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="false">

<!-- diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下: user.home – 用户主目录
user.dir – 用户当前工作目录 java.io.tmpdir – 默认临时文件路径 -->
<diskStore path="java.io.tmpdir/Tmp_EhCache" />

<!-- defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。 -->

<!-- name:缓存名称。 maxElementsInMemory:缓存最大数目 maxElementsOnDisk:硬盘最大缓存个数。 eternal:对象是否永久有效,一但设置了,timeout将不起作用。
overflowToDisk:是否保存到磁盘,当系统当机时 timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts
of the Virtual Machine. The default value is false. diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。 memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。 memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
FIFO,first in first out,这个是大家最熟的,先进先出。 LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。 -->

<!-- 默认配置 -->
<defaultCache eternal="false" maxElementsInMemory="5000"
overflowToDisk="true" diskPersistent="false" timeToIdleSeconds="60"
timeToLiveSeconds="100" diskExpiryThreadIntervalSeconds="100"
memoryStoreEvictionPolicy="LFU" />

<!-- 字典缓存 -->
<cache name="dictionaryCache" eternal="false"
maxElementsInMemory="5000" overflowToDisk="false"
diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="7200"
memoryStoreEvictionPolicy="LRU" />

<!-- 资源缓存 -->
<cache name="cmsResourceCache" eternal="false"
maxElementsInMemory="5000" overflowToDisk="false"
diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="7200"
memoryStoreEvictionPolicy="LRU" />
</ehcache>

3、创建EhcacheConfig工具类

package com.example.demo.common.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

/**
* ehcache 配置
* @author dashen
* @3.0.0
*/
@Configuration
@EnableCaching
public class EhcacheConfig {

/**
*  ehcache 主要的管理器
* @param bean
* @return
*/
@Bean
public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){
return new EhCacheCacheManager(bean.getObject());
}

/**
* 据shared与否的设置,
* Spring分别通过CacheManager.create()
* 或new CacheManager()方式来创建一个ehcache基地.
* 也说是说通过这个来设置cache的基地是这里的Spring独用,还是跟别的(如hibernate的Ehcache共享)
* @return
*/
@Bean
public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){
EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean ();
cacheManagerFactoryBean.setConfigLocation (new ClassPathResource("ehcache.xml"));
cacheManagerFactoryBean.setShared(true);
return cacheManagerFactoryBean;
}
}

4、这个时候基本配置就完成了,缓存信息

package com.ds.tech.service.cache;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.ds.tech.dao.rmdb.CmsResourceCatetoryDao;
import com.ds.tech.dao.rmdb.CmsResourceDao;
import com.ds.tech.entity.rmdb.CmsResource;
import com.ds.tech.entity.rmdb.CmsResourceExample;
import com.ds.tech.utility.log4j2.LogWriter;

@Service
public class EhCacheCmsResource {
@Autowired
CmsResourceDao cmsResourceDao;

/**
* 资源信息缓存
* @return
*/
@Cacheable(value="cmsResourceCache",key="'cmsResource'")
public List<CmsResource> getCmsResourceList(){

List<CmsResource> list = new ArrayList<CmsResource>();

try {
CmsResourceExample example = new CmsResourceExample();
example.setOrderByClause("seq_no asc");
list = cmsResourceDao.selectByExample(example);

if(list == null) {
return new ArrayList<CmsResource>();
}
} catch (Exception e) {
LogWriter.writeErrorLog("读取权限资源缓存异常",e);
}
return list;
}
}

5、 注意:在这个方法中@Cacheable 中的value值要和ehcache.xml中配置的cache的name值相同,这样才会把数据注入到缓存中。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: