Ehcache не работает в кластере / мульти-VM
Я пытаюсь реплицировать кэш для нескольких виртуальных машин, но он не работает..... Но я получаю исключение NPE при попытке поместить элемент в кэш, потому что EhcacheManager ehcacheManager = EhcacheManager.getInstance(); Cache cache = ehcacheManager.getCache(CacheConstant.SAMPLEDISTRIBUTEDCACHE);
кеш возвращается
В pom.xm я использую следующую версию.
// Pom.xml
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.9</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-jgroupsreplication</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.jgroups</groupId>
<artifactId>jgroups</artifactId>
<version>3.5.0.Final</version>
</dependency>
Я создал два сервлета, чтобы поместить и получить элемент из кэша. CacheProducerServlet используется для помещения значения в кэш, а Consumer - для получения / чтения значения из кеша.
изменения в web.xml
<servlet>
<display-name>CacheConsumerServlet</display-name>
<servlet-name>CacheConsumerServlet</servlet-name>
<servlet-class>com.ericsson.fdp.prepaid.rs.servlet.CacheConsumerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CacheConsumerServlet</servlet-name>
<url-pattern>/CacheConsumerServlet</url-pattern>
</servlet-mapping>
<servlet>
<display-name>CacheProducerServlet</display-name>
<servlet-name>CacheProducerServlet</servlet-name>
<servlet-class>com.ericsson.fdp.prepaid.rs.servlet.CacheProducerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CacheProducerServlet</servlet-name>
<url-pattern>/CacheProducerServlet</url-pattern>
</servlet-mapping>
мои изменения в ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true">
<!--
Sets the path to the directory where cache .data files are created. If
the path is a Java System Property it is replaced by its value in the
running VM. The following properties are translated: user.home -
User's home directory user.dir - User's current working directory
java.io.tmpdir - Default temp file path
-->
<diskStore path="${cgw.home}/cache/${cgw.instance.name}/cgw.cache" />
<cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheManagerPeerProviderFactory"
properties="connect=UDP(mcast_addr=127.0.0.1;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=":"
/>
<cache
name="SAMPLEDISTRIBUTEDCACHE"
maxElementsInMemory="500"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="500"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
statistics="true"
>
<cacheEventListenerFactory
class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"
properties="replicateAsynchronously=true, replicatePuts=false,
replicateUpdates=true, replicateUpdatesViaCopy=false,
replicateRemovals=false" />
</cache>
</ehcache>
//CacheProducerServlet.java: использование для помещения значения в кеш
public class CacheProducerServlet extends HttpServlet {
private static Logger loggerManager = Logger.getLogger(CGWContextListener.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
loggerManager.info( "CacheProducerServlet Start Here");
PrintWriter out = null;
String strKey =req.getParameter("key");
loggerManager.info( "CacheProducerServlet Request Key "+strKey);
EhcacheManager ehcacheManager = EhcacheManager.getInstance();
Cache cache = ehcacheManager.getCache(CacheConstant.SAMPLEDISTRIBUTEDCACHE);
loggerManager.info("CacheProducerServlet Cacke "+cache);
loggerManager.info(
"Putting element in cache with key :" + CacheConstant.SAMPLEDISTRIBUTEDCACHE.getValue() + strKey + " And Value is :" + strKey);
ehcacheManager.put(cache, CacheConstant.SAMPLEDISTRIBUTEDCACHE.getValue() + strKey, strKey);
loggerManager.info( "CacheProducerServlet End Here");
resp.setContentType("text/xml");
out = resp.getWriter();
out.println("CacheConsumerServlet Success");
}
}
//CacheConsumerServlet.java: используется для получения значения из кэша
public class CacheConsumerServlet extends HttpServlet {
private static Logger loggerManager = Logger.getLogger(CGWContextListener.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
loggerManager.info( "CacheConsumerServlet Start Here");
PrintWriter out = null;
String strKey = req.getParameter("key");
loggerManager.info( "CacheConsumerServlet Request Key "+strKey);
EhcacheManager ehcacheManager = EhcacheManager.getInstance();
Cache cache = ehcacheManager.getCache(CacheConstant.SAMPLEDISTRIBUTEDCACHE);
loggerManager.info("CacheConsumerServlet Cacke "+cache);
Element element = ehcacheManager.get(cache, CacheConstant.SAMPLEDISTRIBUTEDCACHE.getValue() + strKey);
loggerManager.info("CacheConsumerServlet Element ->"+element.getValue().toString());
loggerManager.info("CacheConsumerServlet Element value ->"+element.getValue().toString());
loggerManager.info("CacheConsumerServlet End Here");
resp.setContentType("text/xml");
out = resp.getWriter();
out.println("CacheConsumerServlet Success");
}
}
//CacheConstant.java
package com.ericsson.fdp.prepaid.core.constants;
public enum CacheConstant {
SAMPLEDISTRIBUTEDCACHE("SAMPLEDISTRIBUTEDCACHE");
private String _value; private CacheConstant (String value) {_value = value; }
public String getValue()
{
return _value;
}
}