ehCache浅谈(转)

简介: ehcache FAQ中提到 Remember that a value in a cache element is globally accessible from multiple threads.

 


ehcache FAQ中提到
Remember that a value in a cache element is globally accessible from multiple threads. It is inherently not thread safe to modify the value . It is safer to retrieve a value, delete the cache element and then reinsert the value.

The UpdatingCacheEntryFactory does work by modifying the contents of values in place in the cache. This is outside of the core of ehcache and is targeted at high performance CacheEntryFactories for SelfPopulatingCaches.

ehcache 是线程安全的吗?
如果一个频繁修改的表,会涉及到多线程,适合放入ehcache吗?(目前就是因为数据库IO压力过大,才想放入缓存)

ehcache查找时key:ID,那么如果我不是以ID为查询条件的话,是否就没有使用到缓存,
例如:我用电话号码来查询用户,发现缓存似乎没有用到,如何才能解决此问题?


Ehcache的类层次模型主要为三层,最上层的是CacheManager,这是操作Ehcache的入口。
可以通过CacheManager.getInstance()获得一个单子的CacheManger,或者通过CacheManger的构造函数创建一个新的CacheManger。
每个CacheManager都管理着多个Cache。
每个Cache都以一种类Hash的方式,关联着多个Element。而Element则是我们用于存放要缓存内容的地方。
在配置EhCache前需要引入两个开发包:ehcache-1.3.0.jar和commons-logging-1.04.jar
https://github.com/ehcache/ehcache3
http://www.ehcache.org/downloads/

Cache的配置很灵活,官方提供的Cache配置方式有好几种。你可以通过声明配置、在xml中配置、在程序里配置或者调用构造方法时传入不同的参数。
你可以将Cache的配置从代码中剥离出来,也可以在使用运行时配置,所谓的运行时配置无非也就是在代码中配置。以下是运行时配置的好处:
在同一个地方配置所有的Cache,这样很容易管理Cache的内存和磁盘消耗。
发布时可更改Cache配置。
可再安装阶段就检查出配置错误信息,而避免了运行时错误。

CacheManager配置
DmulticastGroupPort=4446,这样可以配置监听端口。

DiskStore配置
如果你使用的DiskStore(磁盘缓存),你必须要配置DiskStore配置项。如果不配置,Ehcache将会使用java.io.tmpdir。
diskStroe的“path”属性是用来配置磁盘缓存使用的物理路径的,Ehcache磁盘缓存使用的文件后缀名是.data和.index。
<disStore path=”java.io.tmpdir”/>

name:Cache的唯一标识
maxElementsInMemory:内存中最大缓存对象数。
maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大。
eternal:Element是否永久有效,一但设置了,timeout将不起作用。
overflowToDisk:配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中。
timeToIdleSeconds:设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。 timeToLiveSeconds:设置Element在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大。
diskPersistent:是否缓存虚拟机重启期数据。(这个虚拟机是指什么虚拟机一直没看明白是什么,有高人还希望能指点一二)。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。
你可以设置为FIFO(先进先出)或是LFU(较少使用)。这里比较遗憾,Ehcache并没有提供一个用户定制策略的接口,仅仅支持三种指定策略,感觉做的不够理想。

http://www.cnblogs.com/discuss/articles/1866901.html

配置文件
例子:ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <defaultCache maxElementsInMemory="2" eternal="false"
                  timeToIdleSeconds="1" timeToLiveSeconds="1" overflowToDisk="false"
                  memoryStoreEvictionPolicy="LRU"/>
    <cache name="sampleCache1" maxElementsInMemory="5" eternal="false"
           overflowToDisk="false" timeToIdleSeconds="1" timeToLiveSeconds="1"
           memoryStoreEvictionPolicy="LRU">
    </cache>
</ehcache>

注:
在ehcache的配置文件里面必须配置defaultCache。
每个<cache>标签定义一个新的cache,属性的含义基本上可以从名字上得到,详细的说明可以参考上面的链接。

所以使用EHCache大概的步骤为: 
第一步:生成CacheManager对象 
第二步:生成Cache对象 
第三步:向Cache对象里添加由key,value组成的键值对的Element元素 
示例程序:
例子:

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import java.util.List;

/**
 * Created by MyWorld on 2016/1/20.
 */
public class EHCacheDemo {
    public static void main(String[] args) {
        CacheManager manager = new CacheManager("ehcache.xml");
        Cache cache = manager.getCache("sampleCache1");
        for (int i = 0; i < 6; i++) {
            Element e = new Element("key" + i, "value" + i);
            cache.put(e);
        }

        List keys = cache.getKeys();
        for (Object key : keys) {
            System.out.println(key + "," + cache.get(key));
        }
    }
}

注:程序的流程也是比较明晰的,首先是获取一个CacheManager,这是使用Ehcache的入口,然后通过名字获取某个Cache,然后就可以对Cache存取Element。Cache使用类Hash的方式来管理Element。
事件处理
说明:可以为CacheManager添加事件监听,当对CacheManager增删Cache时,事件处理器将会得到通知。要配置事件处理,需要通过ehcache的配置文件来完成。
配置文件:ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <defaultCache maxElementsInMemory="2" eternal="false"
                  timeToIdleSeconds="1" timeToLiveSeconds="1" overflowToDisk="false"
                  memoryStoreEvictionPolicy="LRU"/>
    <cache name="sampleCache1" maxElementsInMemory="5" eternal="false"
           overflowToDisk="false" timeToIdleSeconds="1" timeToLiveSeconds="1"
           memoryStoreEvictionPolicy="LRU">
        <cacheEventListenerFactory class="ehcache.test.CELF"/>
    </cache>
</ehcache>

 

注:通过<cacheManagerEventListenerFactory>来注册事件处理器的工厂类。
代码:
package ehcache.test;
import java.util.Properties;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.event.CacheEventListener;
import net.sf.ehcache.event.CacheEventListenerFactory;
public class CELF extends CacheEventListenerFactory {
@Override
public CacheEventListener createCacheEventListener(Properties properties) {
return new CEL();
}
}
class CEL implements CacheEventListener {
public void dispose() {}
public void notifyElementEvicted(Ehcache cache, Element element) {}
public void notifyElementExpired(Ehcache cache, Element element) {}
public void notifyElementPut(Ehcache cache, Element element)
throws CacheException {
System.out.println(element.getKey() + " was added.");
}
public void notifyElementRemoved(Ehcache cache, Element element)
throws CacheException {
System.out.println(element.getKey() + " was removed.");
}
public void notifyElementUpdated(Ehcache cache, Element element)
throws CacheException {}
public void notifyRemoveAll(Ehcache cache) {}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
注:这里的代码与之前的类似,由此可见Ehcache的事件处理采用的是一种类plugin方式,也就是说,事件处理的添加是以不修改源代码为前提的。

http://blog.chinaunix.net/uid-20577907-id-2834484.html

1. EHCache 的特点,是一个纯Java ,过程中(也可以理解成插入式)缓存实现,单独安装Ehcache ,需把ehcache-X.X.jar 和相关类库方到classpath中。
如项目已安装了Hibernate ,则不需要做什么。。直接可以使用Ehcache 
Cache 存储方式 :内存或磁盘 

2. 单独使用 EHCache 

使用CacheManager 创建并管理Cache 
1).创建CacheManager有4种方式: 

A:使用默认配置文件创建 
CacheManager manager = CacheManager.create();  

B:使用指定配置文件创建 
CacheManager manager = CacheManager.create("src/config/ehcache.xml");  //这个路径的写法是eclipse中的格式。源码是通过new File的方法来初始化配置文件

C:从classpath中找寻配置文件并创建 

URL url = getClass().getResource("/anothername.xml");
CacheManager manager = CacheManager.create(url);

D:通过输入流创建

InputStream fis = new FileInputStream(new File("src/config/ehcache.xml").getAbsolutePath());
try {
manager = CacheManager.create(fis);
} finally {
fis.close();
}


卸载CacheManager ,关闭Cache 
manager.shutdown();    

2)使用Caches

取得配置文件中预先 定义的sampleCache1设置,通过CacheManager生成一个Cache
Cache cache = manager.getCache("sampleCache1");  
设置一个名为test 的新cache,test属性为默认 

CacheManager manager = CacheManager.create();
manager.addCache("test");

设置一个名为test 的新cache,并定义其属性 

CacheManager manager = CacheManager.create();
Cache cache = new Cache("test", 1, true, false, 5, 2);
manager.addCache(cache);

往cache中加入元素 

Element element = new Element("key1", "value1");
cache.put(new Element(element);

从cache中取得元素
Element element = cache.get("key1");  
http://macrochen.blogdriver.com/macrochen/869480.html 

使用Cache实例来操纵缓存了,主要的方法是:
Cache.get(Object key),
Cache.put(new Element(Object key, Object value)),
Cache.remove(Object key)。  








 

目录
打赏
0
0
0
0
97
分享
相关文章
解决“Unable to start embedded Tomcat“错误的完整指南
通过逐步检查以上问题,你应该能够解决 "Unable to start embedded Tomcat" 错误,并使Tomcat成功启动。
2269 1
解决“Unable to start embedded Tomcat“错误的完整指南
kde
|
21天前
|
Docker镜像加速指南:手把手教你配置国内镜像源
配置国内镜像源可大幅提升 Docker 拉取速度,解决访问 Docker Hub 缓慢问题。本文详解 Linux、Docker Desktop 配置方法,并提供测速对比与常见问题解答,附最新可用镜像源列表,助力高效开发部署。
kde
10924 82
阿里云百炼全新发布Qwen3-Coder-Plu并开源,重磅升级Qwen3-235B
面向全球的智能编程引擎Qwen3-Coder正式开源!首发旗舰版Qwen3-Coder-480B-A35B-Instruct,拥有480B参数、35B有效参数,基于MoE架构,模型在Agentic Coding、浏览器智能操作及基础编码任务中刷新SOTA纪录,并同步开源完整工具链,包括Qwen Code命令行工具、Claude Code集成、VS Code插件及阿里云平台API支持。Qwen3-Coder支持256K上下文,最高可扩展至1M,适用于仓库级代码理解。通过强化学习技术,实现多轮交互与自主决策,大幅提升代码执行成功率。开发者可通过阿里云百炼平台直接体验或调用API使用。
923 0
连续四年,阿里云再获市场份额第一
IDC报告:阿里云再获公有云云工作负载安全市场份额第一!
云上十五年——弹性计算系列客户故事(一)
技术的价值在于解决真实业务挑战。为记录这十五年的共同成长,阿里云特别推出《云上十五年》客户故事专栏,分享与各行业伙伴的实践成果。新起点开启新征程,阿里云持续突破核心技术,让云计算的“澎湃算力”,持续为各行各业提供“创新动力”。
云上十五年——弹性计算系列客户故事(一)
Windows安装Claude Code
Claude Code 是 Anthropic 推出的代码助手,支持在 Windows 通过 WSL(Windows Subsystem for Linux)运行。本文介绍如何在 Windows 系统中启用 WSL、安装 Ubuntu 子系统、配置 Python 与 Node.js 环境,并最终安装和运行 Claude Code。内容涵盖 WSL 设置、开发工具安装、依赖配置及常见问题解决方法,助你顺利在本地环境中使用 Claude Code 提升编码效率。
785 2
Windows安装Claude Code
淘天AB实验分析平台Fluss落地实践:更适合实时OLAP的消息队列
淘天集团数据开发团队基于Fluss构建新一代实时数仓,解决数据消费冗余、探查困难及大State运维难题。Fluss融合列存与实时更新能力,支持列裁剪、KV点查、Delta Join及湖流一体,显著降低IO与计算资源消耗,提升作业稳定性与数据探查效率。已在淘天AB实验平台落地,覆盖搜索、推荐等核心业务,通过618大促验证,实现千万级流量、秒级延迟,资源消耗降低30%,State缩减超100TB。未来将持续深化湖仓架构,拓展AI场景应用。
438 4
淘天AB实验分析平台Fluss落地实践:更适合实时OLAP的消息队列
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等