`

Ehcache集群环境配置

 
阅读更多

Ehcache缓存

概述

Ehcache的类层次模型主要为三层,最上层的是CacheManager,它是操作Ehcache的入口。我们可以通过CacheManager.getInstance()获得一个单CacheManager,或者通过CacheManager的构造函数创建一个新的CacheManager。每个CacheManager都管理着多个Cache。而每个Cache都以一种hash的方式关联着多个Element。而Element则是我们用于存放缓存内容的地方。

 

配置文件(ehcache.xml放置于项目根目录下)

例子:

ehcache.xml

<?xml version="1.0" encoding="UTF-8" ?>
<ehcache
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation=" ehcache.xsd"
updateCheck="true"
monitoring="autodetect"
dynamicConfig="true">
 
<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"/>

</ehcache>

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

 

 

实例程序:

package ehcache.test01;

import java.util.List;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

public class test01 {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		//使用ehcache.xml配置文件创建一个缓存管理器
		CacheManager manager = new CacheManager("ehcache.xml");
		//获得ehcache.xml配置文件中sampleCache1缓存的句柄
		Cache cache = manager.getCache("sampleCache1");
		
		for(int i = 0; i< 10 ; i++){
			Element e = new Element("key"+ i ,"value" + i );
			System.out.println(e.toString());
			cache.put(e);
		}

		//更新一条记录
		cache.put(new Element("key7","NewValue7"));
		
		//根据key取得对应element的序列化value值
		System.out.println("Get Serializable value :  " + cache.get("key7").getValue().toString());
		
        //根据key取得对应element的非序列化value值
		System.out.println("Get Non Serializable value :  " + cache.get("key7").getObjectValue().toString());

		//SampleCache1的配置是支持磁盘持久化的。如果想要保证element即时的被输出到磁盘,可以调用cache.flush();
		//cache.flush();
		
		//获得当前cache中的element数量
		System.out.println("cache size = " + cache.getSize());
		
		//获得当前MemoryStore中的element数量
		System.out.println("cache memorystore size = " + cache.getMemoryStoreSize());
//获得当前DiskStore中element数量
		System.out.println("cache Diskstore size = " + cache.getDiskStoreSize());
		
		List<String> keys = cache.getKeys();
		//System.out.println(cache.getKeys().size());
		for(String key : keys){
			System.out.println(key + "," + cache.get(key));
		}
	}
}

 

环境为两台机器

主机A ip192.168.255.131

主机B ip192.168.255.130

 

1. RMI方式:

rmi的方式配置要点(下面均是server1上的配置,server2上的只需要把ip兑换即可)

 

具体说明:配置cacheManagerPeerListenerFactory是配宿主主机配置监听程序,来发现其他主机发来的同步请求

配置cacheManagerPeerProviderFactory是指定除自身之外的网络群体中其他提供同步的主机列表,用“|”分开不同的主机。

下面的例子的测试过程是:主机B缓存开启,并从名为UserCache的缓存中循环抓取键值为“key1”的元素,直到取到,才退出循环。主机A缓存启动,并在名为UserCache的缓存中放入键值为“key1”的元素。显然,如果主机B取到的元素,那么就证明同步成功,也就是集群成功。

所以在测试过程中先启动主机B的测试程序,在启动主机A的测试程序。

注意:确保你所监听的端口已被服务器打开

下面具体说配置文件以及测试程序:

<!--[if !supportLists]-->1.       1、主机A的配置文件以及测试源代码

recluster_ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       
    xsi:noNamespaceSchemaLocation="ehcache.xsd">       
    <cacheManagerPeerProviderFactory       
        class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
properties="peerDiscovery=manual,rmiUrls=//192.168.255.130:40000/UserCache"/>       
       
    <cacheManagerPeerListenerFactory       
        class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"       
        properties="hostName=192.168.255.131,port=40000,socketTimeoutMillis=120000" />       
    <defaultCache maxElementsInMemory="10000" eternal="false"       
        timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"       
        diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000"       
        diskPersistent="false" diskExpiryThreadIntervalSeconds="120"       
        memoryStoreEvictionPolicy="LRU">       
        <cacheEventListenerFactory       
            class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" />       
    </defaultCache>       
       
    <cache name="UserCache" maxElementsInMemory="1000" eternal="false"       
        timeToIdleSeconds="100000" timeToLiveSeconds="100000"       
        overflowToDisk="false">       
        <cacheEventListenerFactory       
            class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" />       
    </cache>       
</ehcache>

 Java代码

package ehcache;

import java.net.URL;

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

public class clustertest {

	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException{
		// TODO Auto-generated method stub
		//URL url = clustertest.class.getClassLoader().getResource("recluster_ehcache.xml"); 
		CacheManager manager = new CacheManager("recluster_ehcache.xml");
//get Cache        
		Cache cache = manager.getCache("UserCache");        
		Element element = new Element("key1", "value1");   
		cache.put(element);  
		System.out.println("Initial:\n"//+url.toString()
				+"\n"+manager.getName()
				+"\n"+cache.getName()
				+" 's size = "+cache.getSize()
				+"\n"+element.toString());     
		

		Element element1 = cache.get("key1");        
		System.out.println(element1.getValue());   
		//while(true){
		//	Thread.sleep(1000);
		//}
		}
}

 2、 主机B上的配置文件以及测试代码

 

 recluster_ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="ehcache.xsd">
	<cacheManagerPeerProviderFactory
		class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
		properties="peerDiscovery=manual,rmiUrls=//192.168.255.131:40000/UserCache" />

	<cacheManagerPeerListenerFactory
		class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
		properties="hostName=192.168.255.130,port=40000,socketTimeoutMillis=120000" />

	<defaultCache maxElementsInMemory="10000" eternal="false"
		timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
		diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000"
		diskPersistent="false" diskExpiryThreadIntervalSeconds="120"
		memoryStoreEvictionPolicy="LRU">
		<cacheEventListenerFactory
			class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" />
	</defaultCache>

	<cache name="UserCache" maxElementsInMemory="1000" eternal="false"
		timeToIdleSeconds="100000" timeToLiveSeconds="100000"
overflowToDisk="false">
		<cacheEventListenerFactory
			class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" />
	</cache>
</ehcache>

 Java代码

package ehcache;

import java.net.URL;

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

public class cluster_B {

	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		//System.out.println("Test begin");
		//URL url = cluster_B.class.getClassLoader().getResource("recluster_ehcache.xml");   
		CacheManager manager = new CacheManager("recluster_ehcache.xml"); 
		//System.out.println(url.toString());
        //get Cache        
        Cache cache = manager.getCache("UserCache");    
        
        int i=0;
        while(true) {     
        	
        	i++;
        	System.out.println(i+". "+cache.getName()+" 's size = "+cache.getSize());
            Element e = cache.get("key1");        
            if(e != null) {        
                System.out.println(e.getValue());        
                break;        
            }        
            Thread.sleep(1000);        
        }  
	}
}

 主机B上成功取出value1即表示成功

 

2. JGroups方式:

ehcache 1.5.0之后版本支持的一种方式,配置起来比较简单,要点:

 

a. 配置PeerProvider,使用tcp的方式,例子如下:

<cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheManagerPeerProviderFactory"
		properties="connect=TCP(start_port=7800):
        TCPPING(initial_hosts=192.168.2.154[7800],192.168.2.23[7800];port_range=10;timeout=3000;
        num_initial_members=3;up_thread=true;down_thread=true):
        VERIFY_SUSPECT(timeout=1500;down_thread=false;up_thread=false):
        pbcast.NAKACK(down_thread=true;up_thread=true;gc_lag=100;retransmit_timeout=3000):
        pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;shun=false;
        print_local_addr=false;down_thread=true;up_thread=true)" 
        propertySeparator="::" />

 b.为每个cache添加cacheEventListener

<cache name="userCache" maxElementsInMemory="10000" eternal="true"
		overflowToDisk="true" timeToIdleSeconds="0" timeToLiveSeconds="0"
		diskPersistent="false" diskExpiryThreadIntervalSeconds="120">
		<cacheEventListenerFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"
			properties="replicateAsynchronously=true, replicatePuts=true,
   				replicateUpdates=true, replicateUpdatesViaCopy=false, replicateRemovals=true"/>
</cache>

  JGroup方式配置的两个server上的配置文件一样,若有多个server,在initial_hosts中将server ip加上即可。

一个完整的ehcache.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="http://ehcache.sf.net/ehcache.xsd">
	<diskStore path="java.io.tmpdir" />

	<cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheManagerPeerProviderFactory"
		properties="connect=TCP(start_port=7800):
        TCPPING(initial_hosts=192.168.2.154[7800],192.168.2.23[7800];port_range=10;timeout=3000;
        num_initial_members=3;up_thread=true;down_thread=true):
        VERIFY_SUSPECT(timeout=1500;down_thread=false;up_thread=false):
        pbcast.NAKACK(down_thread=true;up_thread=true;gc_lag=100;retransmit_timeout=3000):
        pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;shun=false;
        print_local_addr=false;down_thread=true;up_thread=true)" 
        propertySeparator="::" />
<defaultCache maxElementsInMemory="10000" eternal="true"
		overflowToDisk="true" timeToIdleSeconds="0" timeToLiveSeconds="0"
		diskPersistent="false" diskExpiryThreadIntervalSeconds="120">
		<cacheEventListenerFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"
			properties="replicateAsynchronously=true, replicatePuts=true,
   				replicateUpdates=true, replicateUpdatesViaCopy=false, replicateRemovals=true"/>
	</defaultCache>

	<cache name="velcroCache" maxElementsInMemory="10000" eternal="true"
		overflowToDisk="true" timeToIdleSeconds="0" timeToLiveSeconds="0"
		diskPersistent="false" diskExpiryThreadIntervalSeconds="120">
		<cacheEventListenerFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"
			properties="replicateAsynchronously=true, replicatePuts=true,
   				replicateUpdates=true, replicateUpdatesViaCopy=false, replicateRemovals=true"/>
	</cache>
	<cache name="userCache" maxElementsInMemory="10000" eternal="true"
		overflowToDisk="true" timeToIdleSeconds="0" timeToLiveSeconds="0"
		diskPersistent="false" diskExpiryThreadIntervalSeconds="120">
		<cacheEventListenerFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"
			properties="replicateAsynchronously=true, replicatePuts=true,
   				replicateUpdates=true, replicateUpdatesViaCopy=false, replicateRemovals=true"/>
	</cache>
	<cache name="resourceCache" maxElementsInMemory="10000"
		eternal="true" overflowToDisk="true" timeToIdleSeconds="0"
		timeToLiveSeconds="0" diskPersistent="false"
		diskExpiryThreadIntervalSeconds="120">
		<cacheEventListenerFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"
			properties="replicateAsynchronously=true, replicatePuts=true,
   				replicateUpdates=true, replicateUpdatesViaCopy=false, replicateRemovals=true"/>
	</cache>
</ehcache>

 

 

 

分享到:
评论

相关推荐

    EHcache缓存框架

    EHcache缓存框架,ehcache介绍与说明,Ehcache详细,EHcache集群环境配置

    集群环境中使用_EhCache_缓存系统&Ehcache配置文件的详细说明

    NULL 博文链接:https://jlwangjinshuang-163-com.iteye.com/blog/1058617

    java缓存实现与spring托管

    0. 文档介绍 2 0.1 文档目的 2 0.2 文档范围 2 0.3 读者对象 2 0.4 参考文献 2 0.5 术语与缩写解释 2 1. 概述 3 1.1背景 3 1.2 主要特征 3 ...4. 分布式缓存集群环境配置 19 4.1 集群配置方式 19 5. 测试用例 28

    Ehcache分布式缓存与其在spring中的使用

    主要讲解下encache的原理、分布式缓存集群环境配置、与在spring中的使用

    EHCache详解_技术文档

    详细描述EHCache的用法,和spring的集成,在分布式环境(集群)中的配置

    J2Cache两级缓存框架-其他

    该缓存框架主要用于集群环境中。单机也可使用,用于避免应用重启导致的缓存冷启动后对后端业务的冲击。 数据读取: 读取顺序 -&gt; L1 -&gt; L2 -&gt; DB 数据更新 1、从数据库中读取最新数据,依次更新L1 -&gt; L2 ...

    kaleido-repository:KaleidoFoundry是Java 6+技术基础,具有生产力,可插拔性,可扩展性和可扩展性。 它提供用于配置,缓存,i18n,消息传递的模块...

    从简单开始,当您需要更复杂的体系结构(如集群环境),强大的缓存提供程序解决方案,消息传递系统... kaleido将适合而无需更改Java代码。 主要特点是: 动态和集中式(跨集群或本地)的Configuration管理REST API,...

    Java高并发高性能分布式框架从无到有微服务架构设计.doc

    还有CDN就是用来加速 用户访问的:即用户首先访问到全国各地的CDN节点(使用如ATS、Squid实现),如果C DN没命中,会回源到中央nginx集群,该集群如果没有命中缓存(该集群的缓存不是必须 的,要根据实际命中情况等...

    com.yangc.utils:工作中积累的工具类

    com.yangc.utilsjava工具类作为... 基于redis的工具类,与redis的集群配置无缝结合dbJdbcUtils - 操作jdbc的工具类MongodbUtils - 操作mongodb的工具类emailEmailUtils - 邮件工具类,支持发送带附件的邮件encryptionAe

    spring boot 全面的样例代码

    - chapter2-1-1:[配置文件详解:自定义属性、随机数、多环境配置等](http://blog.didispace.com/springbootproperties/) ### Web开发 - chapter3-1-1:[构建一个较为复杂的RESTful API以及单元测试]...

    jeesuite-libs-其他

    功能列表:cache模块基于配置支持单机、哨兵、分片、集群模式自由切换更加简单的操作API封装一级缓存支持(ehcache &amp; guava cache)、分布式场景多节点自动通知多组缓存配置同时支持 (一个应用多个redis server...

    网络架构师148讲视频课程

    │ 第09节:搭建基础的开发环境.avi │ 第10节:Spring+Mybatis实现DAO.avi │ 第11节:Mybatis的分页实现.avi │ 第12节:Service的实现以及模块化.avi │ 第13节:Spring MVC实现Web层开发.avi │ 第14节:新增和...

    单点登录源码

    单点登录, SSM框架公共模块 ├── zheng-admin -- 后台管理模板 ├── zheng-ui -- 前台thymeleaf模板[端口:1000] ...## 环境搭建(QQ群内有“zheng环境搭建和系统部署文档.doc”) #### 开发工具: ...

    java开源包1

    支持redis的主从集群,可以做读写分离。缓存读取自redis的slave节点,写入到redis的master节点。 Java对象的SQL接口 JoSQL JoSQL(SQLforJavaObjects)为Java开发者提供运用SQL语句来操作Java对象集的能力.利用JoSQL...

    java开源包11

    支持redis的主从集群,可以做读写分离。缓存读取自redis的slave节点,写入到redis的master节点。 Java对象的SQL接口 JoSQL JoSQL(SQLforJavaObjects)为Java开发者提供运用SQL语句来操作Java对象集的能力.利用JoSQL...

    java开源包2

    支持redis的主从集群,可以做读写分离。缓存读取自redis的slave节点,写入到redis的master节点。 Java对象的SQL接口 JoSQL JoSQL(SQLforJavaObjects)为Java开发者提供运用SQL语句来操作Java对象集的能力.利用JoSQL...

    java开源包3

    支持redis的主从集群,可以做读写分离。缓存读取自redis的slave节点,写入到redis的master节点。 Java对象的SQL接口 JoSQL JoSQL(SQLforJavaObjects)为Java开发者提供运用SQL语句来操作Java对象集的能力.利用JoSQL...

    java开源包6

    支持redis的主从集群,可以做读写分离。缓存读取自redis的slave节点,写入到redis的master节点。 Java对象的SQL接口 JoSQL JoSQL(SQLforJavaObjects)为Java开发者提供运用SQL语句来操作Java对象集的能力.利用JoSQL...

    java开源包5

    支持redis的主从集群,可以做读写分离。缓存读取自redis的slave节点,写入到redis的master节点。 Java对象的SQL接口 JoSQL JoSQL(SQLforJavaObjects)为Java开发者提供运用SQL语句来操作Java对象集的能力.利用JoSQL...

Global site tag (gtag.js) - Google Analytics