为了提高系统的运行效率,引入缓存机制,减少数据库访问和磁盘IO。下面说明一下ehcache和spring整合配置。

1.   需要的jar包

slf4j-api-1.6.1.jar

ehcache-core-2.1.0.jar

ehcache-spring-annotations-1.1.2.jar

slf4j-log4j12-1.6.1.jar

spring-context-support-4.0.6.RELEASE.jar

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"> <diskStore path="java.io.tmpdir/ehcache"/> <!-- 默认缓存 -->
<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"/> <!-- 菜单缓存 -->
<cache name="menuCache"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/> </ehcache>

  

参数说明:

<diskStore>:当内存缓存中对象数量超过maxElementsInMemory时,将缓存对象写到磁盘缓存中(需对象实现序列化接口)。

<diskStore path="">:用来配置磁盘缓存使用的物理路径,Ehcache磁盘缓存使用的文件后缀名是*.data和*.index。

name:缓存名称,cache的唯一标识(ehcache会把这个cache放到HashMap里)。

maxElementsOnDisk:磁盘缓存中最多可以存放的元素数量,0表示无穷大。

maxElementsInMemory:内存缓存中最多可以存放的元素数量,若放入Cache中的元素超过这个数值,则有以下两种情况。

1)若overflowToDisk=true,则会将Cache中多出的元素放入磁盘文件中。

2)若overflowToDisk=false,则根据memoryStoreEvictionPolicy策略替换Cache中原有的元素。

Eternal:缓存中对象是否永久有效,即是否永驻内存,true时将忽略timeToIdleSeconds和timeToLiveSeconds。

timeToIdleSeconds:缓存数据在失效前的允许闲置时间(单位:秒),仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,此为可选属性即访问这个cache中元素的最大间隔时间,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除。

timeToLiveSeconds:缓存数据在失效前的允许存活时间(单位:秒),仅当eternal=false时使用,默认值是0表示可存活时间无穷大,即Cache中的某元素从创建到清楚的生存时间,也就是说从创建开始计时,当超过这个时间时,此元素将从Cache中清除。

overflowToDisk:内存不足时,是否启用磁盘缓存(即内存中对象数量达到maxElementsInMemory时,Ehcache会将对象写到磁盘中),会根据标签中path值查找对应的属性值,写入磁盘的文件会放在path文件夹下,文件的名称是cache的名称,后缀名是data。

diskPersistent:是否持久化磁盘缓存,当这个属性的值为true时,系统在初始化时会在磁盘中查找文件名为cache名称,后缀名为index的文件,这个文件中存放了已经持久化在磁盘中的cache的index,找到后会把cache加载到内存,要想把cache真正持久化到磁盘,写程序时注意执行net.sf.ehcache.Cache.put(Element element)后要调用flush()方法。

diskExpiryThreadIntervalSeconds:磁盘缓存的清理线程运行间隔,默认是120秒。

diskSpoolBufferSizeMB:设置DiskStore(磁盘缓存)的缓存区大小,默认是30MB

memoryStoreEvictionPolicy:内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存,共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)。

3.   application_spring_cache.xml

<?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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd"> <cache:annotation-driven cache-manager="cacheManager"/> <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:application/ehcache.xml" />
</bean> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="cacheManagerFactory"/>
</bean> </beans>

  

4.   使用

首先在ehcache.xml中配置缓存策略,即添加一组cache。

业务方法前添加

@Cacheable(value = "SMSConsumerReportListCache", key = "'Consumer:'+#currentConsumer.getConsumerId()+'_pageNumber:'+#pageNumber+'_pageSize:'+#pageSize")
public List<SMSReportVO> getReportList(@NotNull SMSConsumer currentConsumer, @NotNull int pageNumber, @NotNull int pageSize) { 。。。。。。 }

key的使用,作为索引查询缓存数据,下次方法调用时先查询缓存数据,存在即使用,不存在,执行方法,并保存。

@CacheEvict(value = "inboxMessage", key =  "'involveUserId:' + #UserHelper.getSessionUser().getUserId()")
CacheEvict,清空缓存,写上key,清除相关key缓存,
allEntries = true。表示全部清空,默认false

注意:

调用内部方法使用缓存,直接调用是没有经过缓存的,需要注入:ApplicationContext applicationContext,使用applicationContext.getBean(******).方法,调用有效

(个人记录)随机token。缓存:

/**
* Token 实现
*
* @author TCoffee
* @version 1.0
* @since 4.0
*/
@Service
public class TokenServiceImpl implements ITokenService { private static final int MsOf2Days = 172800 * 1000; // 2天的毫秒数
private static final String TOKEN_CACHE_NAME = "tokenCache"; @Autowired
EhCacheCacheManager ehCacheCacheManager; /**
* 获取和保存Token
*
* @param tokenTimeToLiveMs
* @return
*/
@Override
public String getAndStoreToken(Long tokenTimeToLiveMs) {
if (tokenTimeToLiveMs < 1) {
throw new IllegalArgumentException("tokenTimeToLiveMs cannot small then 1");
}
if (tokenTimeToLiveMs > MsOf2Days) {
throw new IllegalArgumentException("tokenTimeToLiveMs cannot large then 2 days");
}
String token = produceToken();
TokenEntity tokenEntity = new TokenEntity();
tokenEntity.setToken(token);
tokenEntity.setProduceTime(System.currentTimeMillis());
tokenEntity.setTokenTimeToLiveMs(tokenTimeToLiveMs);
putTokenCache(token, tokenEntity);
return token;
} /**
* 从缓存中读取 token
*/
protected TokenEntity getTokenCache(String token) {
Ehcache ehcache = getTokenCache();
Element element = ehcache.get(token);
return element == null ? null : (TokenEntity) element.getObjectValue();
} /**
* 将 token 设置到缓存
*
* @param token
* @param tokenEntity
* @return
*/
protected synchronized TokenEntity putTokenCache(String token, TokenEntity tokenEntity) {
Ehcache ehcache = getTokenCache();
Element element = new Element(token, tokenEntity);
element.setTimeToLive(Long.valueOf(tokenEntity.getTokenTimeToLiveMs()).intValue());
ehcache.put(element);
return tokenEntity;
} /**
* 校验Token
*
* @param token
*/
@Override
public boolean validateToken(String token) {
TokenEntity tokenEntity = getTokenCache(token);
if (tokenEntity == null) {
return false;
}
if (System.currentTimeMillis() - tokenEntity.getProduceTime() > tokenEntity.getTokenTimeToLiveMs()) {
return false;
}
return true;
} /**
* 设置数据到 token缓存
*
* @param data
* @param token
* @return
*/
@Override
public boolean setTokenData(Map<String, Object> data, String token) {
TokenEntity tokenEntity = getTokenCache(token);
if (tokenEntity == null) {
return false;
}
tokenEntity.setDataMap(data);
putTokenCache(token, tokenEntity);
return true;
} /**
* 从 token 缓存获取数据
*
* @param token
* @return
* @throws InvalidTokenException
*/
@Override
public Map<String, Object> getTokenData(String token) throws InvalidTokenException {
TokenEntity tokenEntity = getTokenCache(token);
if (tokenEntity == null) {
throw new InvalidTokenException("token invalid");
}
return Collections.unmodifiableMap(tokenEntity.getDataMap());
} /**
* 从 token 缓存获取数据
*
* @param key
* @param token
* @param <T>
* @return
* @throws InvalidTokenException
*/
@Override
public <T> T getTokenData(String key, String token) throws InvalidTokenException {
Map<String, Object> map = getTokenData(token);
return (T) map.get(key);
} /**
* 设置数据到 token 缓存
*
* @param key
* @param data
* @param token
* @return
*/
@Override
public boolean setTokenData(String key, Object data, String token) {
TokenEntity tokenEntity = getTokenCache(token);
if (tokenEntity == null) {
return false;
}
tokenEntity.getDataMap().put(key, data);
putTokenCache(token, tokenEntity);
return true;
} /**
* 销毁token数据
*
* @param token
*/
@Override
public void cleanToken(String token) {
getTokenCache().remove(token);
} private Ehcache getTokenCache() {
Ehcache ehcache = ehCacheCacheManager.getCacheManager().getEhcache(TOKEN_CACHE_NAME);
if (ehcache == null) {
throw new RuntimeException("cache not found, cache name:" + TOKEN_CACHE_NAME);
}
return ehcache;
} /**
* 产生token
*
* @return
*/
private String produceToken() {
String token = UUID.randomUUID() + RandomStringUtils.randomAlphabetic(32);
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
BASE64Encoder base64Encoder = new BASE64Encoder();
return base64Encoder.encode(md5.digest(token.getBytes("UTF-8")));
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
throw new RuntimeException("token generate exception", e);
}
}
}

  

Ehcache整合spring配置,配置springMVC缓存的更多相关文章

  1. Ehcache 整合Spring 使用页面、对象缓存

    Ehcache 整合Spring 使用页面.对象缓存 Ehcache在很多项目中都出现过,用法也比较简单.一 般的加些配置就可以了,而且Ehcache可以对页面.对象.数据进行缓存,同时支持集群/分布 ...

  2. Ehcache学习总结(3)--Ehcache 整合Spring 使用页面、对象缓存

    Ehcache 整合Spring 使用页面.对象缓存 Ehcache在很多项目中都出现过,用法也比较简单.一般的加些配置就可以了,而且Ehcache可以对页面.对象.数据进行缓存,同时支持集群/分布式 ...

  3. ehcache整合spring本地接口方式

    一.简介 ehcache整合spring,可以通过使用echache的本地接口,从而达到定制的目的.在方法中根据业务逻辑进行判断,从缓存中获取数据或将数据保存到缓存.这样让程序变得更加灵活. 本例子使 ...

  4. e3mall商城的归纳总结9之activemq整合spring、redis的缓存

    敬给读者 本节主要给大家说一下activemq整合spring,该如何进行配置,上一节我们说了activemq的搭建和测试(单独测试),想看的可以点击时空隧道前去查看.讲完了之后我们还说一说在项目中使 ...

  5. Ehcache整合spring配置

    为了提高系统的运行效率,引入缓存机制,减少数据库访问和磁盘IO.下面说明一下ehcache和spring整合配置. 1.   需要的jar包 slf4j-api-1.6.1.jar ehcache-c ...

  6. Ehcache学习总结(2)--Ehcache整合spring配置

    首先需要的maven依赖为: [html] view plain copy <!--ehcache--> <dependency> <groupId>com.goo ...

  7. (转)Ehcache 整合Spring 使用页面、对象缓存

    Ehcache在很多项目中都出现过,用法也比较简单.一般的加些配置就可以了,而且Ehcache可以对页面.对象.数据进行缓存,同时支持集群/分布式缓存.如果整合Spring.Hibernate也非常的 ...

  8. Ehcache 整合Spring 使用页面、对象缓存(转载)

    Ehcache在很多项目中都出现过,用法也比较简单.一般的加些配置就可以了,而且Ehcache可以对页面.对象.数据进行缓存,同时支持集群/分布式缓存.如果整合Spring.Hibernate也非常的 ...

  9. Ehcache 整合Spring 使用页面、对象缓存(转)

    Ehcache在很多项目中都出现过,用法也比较简单.一般的加些配置就可以了,而且Ehcache可以对页面.对象.数据进行缓存,同时支持集群/分布式缓存.如果整合Spring.Hibernate也非常的 ...

随机推荐

  1. BZOJ 1594 [Usaco2008 Jan]猜数游戏(线段数)

    1594: [Usaco2008 Jan]猜数游戏 Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 626  Solved: 260[Submit][S ...

  2. AES对称加密util

    package cn.com.qmhd.oto.common; import java.security.Key; import java.security.NoSuchAlgorithmExcept ...

  3. python基础6(函数 Ⅰ)

    函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段 定义 def function_name(args...): function_body #例子 def print_somethin ...

  4. 紫书 习题 8-23 UVa 1623 (set妙用 + 贪心)

    这道题我是从样例中看出思路了 2 4 0 0 1 1 看这组数据, 输出的是No, 为什么呢?因为两个1之间没有神龙喝水, 所以一定会有水灾. 然后就启发了我,两次同一个湖的降水之间必须至少有一次神龙 ...

  5. #error 、 #line 和 #pragma 的使用

    1. #error 的用法 (1)#error 是一种预编译器指示字,用于生成一个编译错误消息 (2)用法:#error message //注意:message 不需要用双引号包围 (3)#erro ...

  6. BNUOJ 34990 Justice String

    Justice String Time Limit: 2000ms Memory Limit: 65536KB 64-bit integer IO format: %lld      Java cla ...

  7. ios面试题1

    iOS面试题   1.写一个NSString类的实现 + (id)initWithCString:(c*****t char *)nullTerminatedCString encoding:(NSS ...

  8. 在Windows上面安装多个Memcached

    在Windows上面安装多个Memcached sc create "memcached Server3" start= auto binPath= "D:\memcac ...

  9. max带来的冲突

    题目要求: /* * Copyright (c) 2014, 烟台大学计算机学院 * All rights reserved. * 文件名:sum123.cpp * 作 者:林海云 * 完毕日期:20 ...

  10. HDU 3016 Man Down(线段树)

    HDU 3016 Man Down 题目链接 题意:是男人就下100层的游戏的简单版,每次仅仅能从两端下落.求落地最大血量 思路:利用线段树能够处理出每一个线段能来自哪几个线段.然后就是dag最长路了 ...