本文分享一下ehcache的使用心得,本文主要讲以广播的形式同步缓存。

下面讲述主要分为两个部分,一个是配置文件,一个是Java代码。

1.准备jar包:

slf4j-api-1.7.12.jar,ehcache-core-2.4.3.jar,ehcache-web-2.0.4.jar
备注:1) 版本可以不同
2)sl4j可能与JavaEE6.0中的冲突,在JVM中运行时可以不使用。

2.配置文件:

2.1. 完整xml(广播形式)

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
http://www.springmodules.org/schema/cache/springmodules-cache.xsd
http://www.springmodules.org/schema/ www.wanmeiyule11.cn cache/springmodules-ehcache.xsd"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!-- 默认缓存 -->
<defaultCache eternal="false" maxElementsInMemory="10000"
overflowToDisk="false" timeToIdleSeconds="0" timeToLiveSeconds="0"
memoryStoreEvictionPolicy="LFU" />
<!-- 自定义缓存 -->
<cache name="myCache" eternal="true" maxElementsInMemory="10000"
overflowToDisk="false" timeToIdleSeconds="0" timeToLiveSeconds="0"
memoryStoreEvictionPolicy="LFU">
<!-- 监听RMI同步缓存对象配置 注册相应的的缓存监听类,用于处理缓存事件,如put,remove,update,和expire -->
<cacheEventListenerFactory
class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
properties="replicateAsynchronously=true, replicatePuts=true,
replicatePutsViaCopy=true, replicateUpdates=true,
replicateUpdatesViaCopy=true, replicateRemovals=true,
asynchronousReplicationIntervalMillis=200"/>
<!-- 用于在初始化缓存,以及自动设置 -->
<bootstrapCacheLoaderFactory
class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"/>
</cache>
<!--搜索某个网段上的缓存
timeToLive
0是限制在同一个服务器
1是限制在同一个子网
32是限制在同一个网站
64是限制在同一个region
128是限制在同一个大洲
255是不限制-->
<cacheManagerPeerProviderFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory" properties="peerDiscovery=automatic,ysylcsvip.cn multicastGroupAddress=230.0.0.1,multicastGroupPort=4446,timeToLive=32,hostName=localhost" />
<cacheManagerPeerListenerFactory
class="net.sf.ehcache.distribution. www.ysylcsvip.cn RMICacheManagerPeerListenerFactory" />
2.1. 关键部分
ehcache
|——defaultCache (默认cache配置)
|——cache (自定义cache)
|——|——cacheEventListenerFactory(同步动作)
|——|——bootstrapCacheLoaderFactory(工厂是指启动是指一启动就同步数据)
|——cacheManagerPeerProviderFactory(发布:广播)
|——cacheManagerPeerListenerFactory(监听)
同步缓存必须有的几个部分:

1)cacheEventListenerFactory
每个要进行同步的cache都需要设置一个用来向CacheManagerr的成员复制消息的缓存事件监听器。这个工作要通过为每个cache的配置增加一个cacheEventListenerFactory元素来完成。

<cacheEventListenerFactory
class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
properties="replicateAsynchronously=true, replicatePuts=true,
replicatePutsViaCopy=true, replicateUpdates=true,
replicateUpdatesViaCopy=true, replicateRemovals=true,
class – 使用net.sf.ehcache.distribution.RMICacheReplicatorFactory

这个工厂支持以下属性:
replicatePuts=true | false – 当一个新元素增加到缓存中的时候是否要复制到其他的peers. 默认是true。
replicateUpdates=true | false – 当一个已经在缓存中存在的元素被覆盖时是否要进行复制。默认是true。
replicateRemovals= true | false – 当元素移除的时候是否进行复制。默认是true。
replicateAsynchronously=true | false – 复制方式是异步的(指定为true时)还是同步的(指定为false时)。默认是true。
replicatePutsViaCopy=true | false – 当一个新增元素被拷贝到其他的cache中时是否进行复制指定为true时为复制,默认是true。
replicateUpdatesViaCopy=true www.vboyule66.cn | false – 当一个元素被拷贝到其他的cache中时是否进行复制(指定为true时为复制),默认是true。

2)cacheManagerPeerProviderFactory(广播方式)
自动方式:自动发现方式使用tcp广播来建立和包含一个广播组,它的特征是最小配置和对成员组的自动添加和管理。没有那个服务器是有优先级的。对等点每一秒中向广播组发送心跳,如果一个对等点在五秒钟内没发送过来,则此对等点将会被删除,如果有新的,则会被加入集群

<cacheManagerPeerProviderFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"

peerDiscovery 方式:atutomatic 为自动 ;mulicastGroupAddress 广播组地址:230.0.0.1;mulicastGroupPort 广播组端口:40001;timeToLive是指搜索范围:0是同一台服务器,1是同一个子网,32是指同一站点,64是指同一块地域,128是同一块大陆,还有个256,我就不说了;hostName:主机名或者ip,用来接受或者发送信息的接口

3)cacheManagerPeerListenerFactory
将方式配好之后需要配置listener才会有用,接下来讲讲:Listener
Listener是用来监听从集群发送过来的信息
Listenner有两个属性:class和propertis
class 一个完整的工厂类名
properties 都好分割的对facotory有用的属性

<cacheManagerPeerListenerFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" />
1
2
1
2
hostName指的是本机,这里注意如果使用的localhost,则只会对本机有效,请使用子网内的ip地址或者主机名,port端口 40001,socketTimeoutMillis是指socket子模块的超时时间,默认是2000ms,注意port两台主机可以相同可以不同。最好相同,个人建议.

参考文档
1.分布式缓存
2.实例项目
3.实例项目(推荐)
4.详细介绍
5.IBM版介绍

2.Java代码

客户机1

package src.text;

import java.lang.management.ManagementFactory;

import javax.management.MBeanServer;

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

public class EHCacheTest {
private static CacheManager manager = null; // 缓存工厂

public static void main(String[] args) {
EHCacheTest ehCacheTest = new EHCacheTest();
ehCacheTest.init();
}

protected void init() {
// 读入配置
String path = this.getClass().getClassLoader().getResource("").getPath() + "ehcache.xml";
manager = CacheManager.create(path);

// 打印初始缓存
String[] cacheNames = manager.getCacheNames();
printNames(cacheNames);
// 移除缓存
// cacheManager.removeCache("sampleDistributedCache1");
cacheNames = manager.getCacheNames();
printNames(cacheNames);
// distributed -- rmi同步
Cache cache = manager.getCache("fhxxCache");
// 注册被管理的Bean
// JMX -- jconsole(MBeanServer)
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ManagementService.registerMBeans(manager, mBeanServer, true, true, true, true);
for (int i = 0; i < 100000; i++) {
Element temp = cache.get("ehcache");
System.out.println("cache.getSize()=" + cache.getSize());
cache.put(new Element(i, i));
System.out.println("=======================");
System.out.println("第" + i + "次cache.put");
if (temp != null) {
System.out.println(temp.getObjectValue());
} else {
System.out.println("NotFound");
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

private static void printNames(String[] names) {
System.out.println("=======================");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
客户机2

package src.text;

import java.lang.management.ManagementFactory;

import javax.management.MBeanServer;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.Statistics;
import net.sf.ehcache.management.ManagementService;

public class EHCacheTest2 {
private static CacheManager manager = null; // 缓存工厂

public static void main(String[] args) {
EHCacheTest2 ehCacheTest2 = new EHCacheTest2();
ehCacheTest2.init();
}

protected void init() {
// 读入配置
String path = this.getClass().getClassLoader().getResource("").getPath() + "ehcache.xml";
manager = CacheManager.create(path);

// 打印初始缓存
String[] cacheNames = manager.getCacheNames();
// 注册管理Bean
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ManagementService.registerMBeans(manager, mBeanServer, true, true, true, true);
// distributed
Cache cache = manager.getCache("fhxxCache");
// 添加值后另一个虚拟机的缓存通过RMI会同步缓存,并读到这个值
cache.put(new Element("ehcache", "newaddvalue11"));
printCache(cache);
for (int i = 0; i < 10000; i++) {
try {
cache.put(new Element("ehcache", "newaddvalue" + i));
Thread.sleep(3000);
System.out.println("第" + i + "次加载cache.size=" + cache.getSize());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

private static void printCache(Cache cache) {
int size = cache.getSize();
long memSize = cache.getMemoryStoreSize();
long diskSize = cache.getDiskStoreSize();
Statistics stat = cache.getStatistics();
StringBuilder sb = new StringBuilder();
sb.append("size=" + size + ";memsize=" + memSize);
sb.append(";diskSize=" + diskSize + ";");

运行客户机1,开始:

第0次cache.put
NotFound

客户机2,开始后,客户机1

=======================
第29次cache.put
newaddvalue3

本文分享一下ehcache的使用心得,本文主要讲以广播的形式同步缓存。的更多相关文章

  1. Java 写一段字符到指定的文本文档中,如果该文本文档不存在,则创建该文本文档

    写一段字符到指定的文本文档中,如果该文本文档不存在,则创建该文本文档 import java.io.File; import java.io.FileNotFoundException; import ...

  2. c#读取文本文档实践3-写入到文本本文档

    首先通过File.ReadAllLines()方法读入文本文档中内容并返回字符串数组contents,这样每行数据就成为了这个字符串数组contents的一个元素,再利用split()方法将每一个元素 ...

  3. 分享一下学习css,js心得

    简化代码,使页面简洁! web前端开发——将界面更好呈现给用户! 要了解在不同浏览器上的兼容情况.渲染原理和存在的bug! 网站性能优化.SEO: 代码的可维护性.性能: 网站重构的本质:建立一个前端 ...

  4. 分享一个Panda C-60 维修心得

    昨天丰臣国际搞了个汽车后备箱市场,说白了就是一帮闲的没事儿的"白领"大热天把自家闲置的东西拿过来练练摊,这个形式还是不错的,中间看到了一个熊猫的CD机,一眼就看上了,虽说CD早就过 ...

  5. 分享一些关于Lucene的心得

    Lucene的概述 Lucene是一个全文搜索框架,而不是应用产品.因此它并不像http://www.baidu.com/ 或者google Desktop那么拿来就能用,它只是提供了一种工具让你能实 ...

  6. Ehcache jgroups方式同步缓存出现问题总结

    ehcache配置文件按官网配置如下: <?xml version="1.0" encoding="UTF-8"?> <ehcache> ...

  7. 写一些脚本的心得总结系列第4篇-------从数据库同步到redis

    5.从数据库同步到redis的. redis把数据放内存里,读取都非常方便,也提供了远超memcache的丰富数据结构.下面我举2个例子,比如1)把数据从数据库写入到redis: <?php $ ...

  8. [转帖]unity3D OnTriggerEnter和OnCollisionEnter的一点个人心得(主要讲区别)

    觉得这个讲的挺好的,就转过来了:) 太抽象的理论总是让人眼花缭乱,所以我这里以例证为主. 1,测试OnTriggerEnter和OnCollisionEnter的区别 测试:如果两个物体A,B 两者都 ...

  9. wemall app商城源码Android之ListView异步加载网络图片(优化缓存机制)

    wemall-mobile是基于WeMall的android app商城,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可定制修改.本文分享wemall app商城源码Android之L ...

随机推荐

  1. POJ1012(约瑟夫问题)

    1.题目链接地址 http://poj.org/problem?id=1012 2k个人,前面k个是好人,后面k个是坏人,找一个数t,每数到第t时就去掉,使所有坏人在好人之前被杀掉. 思路:约瑟夫公式 ...

  2. Python嵌套、递归、高阶函数

    一.嵌套函数 1.嵌套函数简单的理解可以看作是在函数的内部再定义函数,实现函数的“私有”. 2.特点: <1> 函数内部可以再次定义函数. <2> 只有被调用时才会执行(外部函 ...

  3. java基础之JDBC八:Druid连接池的使用

    基本使用代码: /** * Druid连接池及简单工具类的使用 */ public class Test{ public static void main(String[] args) { Conne ...

  4. Log4j配置很详细

    来自: http://www.blogjava.net/zJun/archive/2006/06/28/55511.html Log4J的配置文件(Configuration File)就是用来设置记 ...

  5. Linux Resin4.0 安装配置

    Resin,是一个非常流行的application server,对servlet和JSP提供了良好的支持,性能优良,resin自身采用Java语言开发.Resin Pro版本支持缓存和负载均衡,收费 ...

  6. Catalan数计算及应用

    Catalan数列是非常奇妙的一列数字,因为很多问题的解就是一个Catalan数.知道了这一规律,很多看似复杂的问题便可迎刃而解.那么什么是Catalan数,什么样的问题的解是Catalan数呢? 1 ...

  7. Leetcode:Regular Expression Matching分析和实现

    题目大意是要求我们实现一个简单的正则表达式全匹配判断.其中正则表达式中只包含一般字符,以及全匹配字符.和变长字符*.其中.可以匹配一个字符,而*与前一个字符相关联,x*可以被看作任意多个x(0到正无穷 ...

  8. python子进程模块subprocess详解与应用实例 之二

    1.2. Popen 对象 Popen类的实例有下列方法: 1. Popen.poll() 检查子进程是否已经结束,设置并返回返回码值. 2. Popen.wait() 等待子进程结束,设置并返回返回 ...

  9. bootstrap中的data-dismiss属性

    <button type="button" class="btn default" data-dismiss="modal">关 ...

  10. 17-取石子-hdu1846(巴什博奕)

    http://acm.hdu.edu.cn/showproblem.php?pid=1846 Brave Game Time Limit: 1000/1000 MS (Java/Others)     ...