Ehcache 下 用jgroup进行复制,Ehcache集群

来源:互联网 发布:perl语言编程 编辑:程序博客网 时间:2024/06/13 10:24

从官方文档上了解到 用RMI 比较简单,按官方的配置,试了n遍都不成功。配置和网上的一样,还是不行,对rmi没有兴趣了,转用Jgroup.

1. 下载资源

Jgroup, http://sourceforge.net/projects/javagroups/files/JGroups/2.12.1.Final/jgroups-2.12.1.Final.jar/download

我的ehcache用的是2.4.2 Jgroup 要用2.1,我试了用 jgroup3.0 会报错。

ehcache-jgroupsreplication-1.4

http://ehcache.org/downloads/destination?name=ehcache-jgroupsreplication-1.4-distribution.tar.gz&bucket=tcdistributions&file=ehcache-jgroupsreplication-1.4-distribution.tar.gz

2. ehcache.xml ,放到classpath下,配置如下:

<?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"><!-- Cache配置            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并没有提供一个用户定制策略的接口,仅仅支持三种指定策略,感觉做的不够理想。           1分钟=60s         5分钟=300s         30分钟=1800s         1小时=3600s         12小时=43200s         1天=86400s         2天=172800s -->    <diskStore path="C:/cachetest"/>        <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheManagerPeerProviderFactory"    properties="connect=UDP(mcast_addr=231.12.21.132;mcast_port=45566;ip_ttl=32;    mcast_send_buf_size=150000;mcast_recv_buf_size=80000):    PING(timeout=2000;num_initial_members=6):    MERGE2(min_interval=5000;max_interval=10000):    FD_SOCK:VERIFY_SUSPECT(timeout=1500):    pbcast.NAKACK(gc_lag=10;retransmit_timeout=3000):    UNICAST(timeout=5000):    pbcast.STABLE(desired_avg_gossip=20000):    FRAG:    pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;    shun=false;print_local_addr=true)"    propertySeparator="::"  />            <defaultCache            maxElementsInMemory="100"            eternal="false"            timeToIdleSeconds="120"            timeToLiveSeconds="120"            overflowToDisk="true"            diskSpoolBufferSizeMB="30"            maxElementsOnDisk="10000"            diskPersistent="false"            diskExpiryThreadIntervalSeconds="120"            memoryStoreEvictionPolicy="LRU" /> <!-- 首页缓存 -->     <cache name="Cache_Test"            maxElementsInMemory="5"            eternal="false"            timeToIdleSeconds="43200"            timeToLiveSeconds="43200"            overflowToDisk="true"            diskSpoolBufferSizeMB="10"            maxElementsOnDisk="10"            diskPersistent="false"            diskExpiryThreadIntervalSeconds="120"            memoryStoreEvictionPolicy="LRU">            <cacheEventListenerFactory    class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"    properties="replicateAsynchronously=true, replicatePuts=true,      replicateUpdates=true, replicateUpdatesViaCopy=false,      replicateRemovals=true" />      </cache>       </ehcache>

测试代码:

package com.test.ehcache;import java.util.List;import net.sf.ehcache.Cache;import net.sf.ehcache.CacheManager;import net.sf.ehcache.Element;public class CacheLocalManager {private static final CacheManager cacheManager = new CacheManager();public CacheLocalManager() {// TODO Auto-generated constructor stub}public static CacheManager getCacheManager() {return cacheManager;}public static Cache getCache(String cacheName) {return getCacheManager().getCache(cacheName);}public static Object readCache(String key, String cacheName){try {Cache cache = getCache(cacheName);Element element = cache.get(key);if (element != null) {return element.getValue();}} catch (Exception e) {e.printStackTrace();}return null;}public static boolean removeCache(String key, String cacheName){try {Cache cache = getCache(cacheName);cache.remove(key);cache.flush();} catch (Exception e) {e.printStackTrace();return false;}return true;}public static boolean saveCache(String key, Object value, String cacheName){try {Cache cache = getCache(cacheName);Element element = new Element(key,value);cache.put(element);} catch (Exception e) {e.printStackTrace();return false;}return true;}public static boolean removeAllCache(String cacheName) {try {Cache cache = getCache(cacheName);cache.removeAll();cache.flush();} catch (Exception e) {e.printStackTrace();return false;}return true;}public static int cacheSize(String cacheName) {try {Cache cache = getCache(cacheName);return cache.getSize();} catch (Exception e) {e.printStackTrace();return 0;}}public static List<String> getCacheKeys(String cacheName) {try {Cache cache = getCache(cacheName);return cache.getKeys();} catch (Exception e) {e.printStackTrace();return null;}}}

package com.test.ehcache;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class Cache extends HttpServlet {/** * Constructor of the object. */public Cache() {super();}/** * Destruction of the servlet. <br> */public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();String action = request.getParameter("action");if(action.equals("read")){String value = (String)CacheLocalManager.readCache("key", "Cache_Test");out.print("cache data==>"+value);}if(action.equals("write")){CacheLocalManager.saveCache("key", "cache test", "Cache_Test");out.print("write ok");}if(action.equals("clear")){CacheLocalManager.removeCache("key", "Cache_Test");out.print("clear ok");}out.flush();out.close();}/** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");out.println("<HTML>");out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");out.println("  <BODY>");out.print("    This is ");out.print(this.getClass());out.println(", using the POST method");out.println("  </BODY>");out.println("</HTML>");out.flush();out.close();}/** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */public void init() throws ServletException {// Put your code here}}

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>    <a href="Cache?action=read">read</a><a href="Cache?action=write">write</a>    <a href="Cache?action=clear">clear</a>  </body></html>

jar包为:

dom4j-1.6.1.jar

ehcache-core-2.4.2.jar

ehcache-terracotta-2.4.2.jar

log4j-1.2.13.jar

slf4j-api-1.6.1.jar

slf4j-simple-1.6.1.jar

ehcache-jgroupsreplication-1.4.jar

jgroups-2.12.1.Final.jar


原创粉丝点击