Ehcache 集群示例系列2:RMI automatic方式(自动发现方式)

来源:互联网 发布:php error log 日志 编辑:程序博客网 时间:2024/06/05 00:39

接上篇ehcache集群时,使用RMI方式中的手动发现节点示例.(链接地址:点击打开链接)

同样,分别用两台计算机来测试.IP地址分别为:192.168.1.200,192.168.1.201.


一.新建一个main类,内容和上篇中的差不多,不同之处是使用的ehcache配置不同.

 
import java.net.URL;import java.net.UnknownHostException;import com.ehUtils.BaseCacheManager;/** * 自动发现节点模式,每个节点计算机共用一个配置文件,和手动发现的一个区别 *  * @author yuansq 2013-9-27 *  */public class EhcacheClusterRMIAuto extends BaseCacheManager {public static void main(String[] args) throws UnknownHostException, InterruptedException {EhcacheClusterRMIAuto cluster = new EhcacheClusterRMIAuto();String ehcacheConfigFile = null;if (args.length == 1) {ehcacheConfigFile = args[0];} else {ehcacheConfigFile = "EhcacheClusterRMIAutomatic.xml";}URL configUrl = cluster.setEhcacheConfig(ehcacheConfigFile);cluster.createMessage(configUrl, 2);}}

二.ehcache配置文件
<?xml version="1.0" encoding="gbk"?><ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd"><diskStore path="java.io.tmpdir" /><cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory" properties="peerDiscovery=automatic,multicastGroupAddress=230.0.0.1,multicastGroupPort=4446" /><cacheManagerPeerListenerFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" /><defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="30" timeToLiveSeconds="30" overflowToDisk="false" /><cache name="replicationCache1" maxElementsInMemory="10000" eternal="false" overflowToDisk="false" timeToIdleSeconds="1800" timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LFU"><cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"properties="replicateAsynchronously=true,replicatePuts=true,replicatePutsViaCopy=true,replicateUpdates=true,replicateUpdatesViaCopy=true,replicateRemovals=true,asynchronousReplicationIntervalMillis=200"propertySeparator="," /><bootstrapCacheLoaderFactory class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory" /></cache><cache name="replicationCache2" maxElementsInMemory="10000" eternal="false" overflowToDisk="false" timeToIdleSeconds="1800" timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LFU"><cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"properties="replicateAsynchronously=true,replicatePuts=true,                            replicatePutsViaCopy=true, replicateUpdates=true,                            replicateUpdatesViaCopy=true, replicateRemovals=true,                            asynchronousReplicationIntervalMillis=200"propertySeparator="," /><bootstrapCacheLoaderFactory class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory" /></cache><cache name="cache3" maxElementsInMemory="10000" eternal="false" overflowToDisk="false" timeToIdleSeconds="1800" timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LFU"></cache></ehcache>

RMI手动和自动自动发现的区别在于:

cacheManagerPeerProviderFactory 的配置,主要是

properties属性的设置不同.

三、
类BaseCacheManager源码:
import java.net.Inet4Address;import java.net.Inet6Address;import java.net.InetAddress;import java.net.URL;import java.net.UnknownHostException;import java.util.List;import net.sf.ehcache.Cache;import net.sf.ehcache.CacheManager;import net.sf.ehcache.Element;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * 生成并读取缓存key *  * @author yuansq 2013-9-24 *  */public class BaseCacheManager {private final static Logger LOG = LoggerFactory.getLogger(BaseCacheManager.class);/** * 获取配置文件URL *  * @param classPathFile *            在src目录下 * @return */public URL setEhcacheConfig(String classPathFile) {ClassLoader cl = Thread.currentThread().getContextClassLoader();LOG.info("配置文件路径:{} ", classPathFile);URL url = cl.getResource(classPathFile);return url;}/** *  * @param ehcacheURL *            ehcache配置文件的URL * @param putSecond *            间隔多少秒存新值(可理解为刷屏) * @throws UnknownHostException * @throws InterruptedException */@SuppressWarnings("rawtypes")public void createMessage(URL ehcacheURL, int putSecond) throws UnknownHostException, InterruptedException {String localhostIp = InetAddress.getLocalHost().getHostAddress();LOG.info("当前计算机IP:{}", localhostIp);LOG.info("ip4地址:{},ip6地址:{}", Inet4Address.getLocalHost().getHostAddress(), Inet6Address.getLocalHost().getHostAddress());CacheManager cm = new CacheManager(ehcacheURL);String[] cacheNames = cm.getCacheNames();LOG.info("获取cache数量:{}", cacheNames.length);if (cacheNames.length > 0) {int seq = 0;while (true) {Thread.sleep(putSecond * 1000);LOG.info("循环所有的cache\n");for (String name : cacheNames) {Cache cache = cm.getCache(name);cache.put(new Element(localhostIp, seq++));List keys = cache.getKeys();StringBuilder kv = new StringBuilder();kv.append("{ ");for (Object eleName : keys) {Element ele = cache.get(eleName);kv.append(ele.getObjectKey()).append(":").append(ele.getObjectValue()).append(",");}kv.delete(kv.length() - 1, kv.length());kv.append("}");LOG.info("缓存name={},内容={}\n", name, kv.toString());kv.delete(0, kv.length());}}}}}


五、效果图

另一张是变更了log4j.xml的输出级别为debug后的日志截图


如果rmi方式手动发现能正常同步的话,手动方式基本上也只是修改一下配置文件即可。

可能出现的错误情况是,使用ipv6,所以要运行时要修改参数。-Djava.net.preferIPv4Stack=true 如:java -jar  -Djava.net.preferIPv4Stack=true  **.jar

下一篇,ehcache 基本JGroups实现集群同步,采用TCP协议。


原创粉丝点击