来源:周成立博客
如何在WebLogic 8.1上使用EhCache分布式缓存
在WebLogic8.1上部署EhCache分布式缓存时,会抛出异常java.lang.ClassNotFoundException: net.sf.ehcache.distribution.RMICachePeer_Stub(no security manager: RMI class loader disabled)。
即因为安全问题找不到RMICachePeer_Stub类,一个比较简单的解决方法就是将ehcache放到CLASSPATH中。
首先将ehcache-1.4.1.jar、commons-logging-1.0.4.jar、backport-util-concurrent-3.1.jar拷贝到一个指定目录(ehcache-1.4.1.jar依赖commons-logging-1.0.4.jar和backport-util-concurrent-3.1.jar,所以一并加入),这里拷贝到WL_HOME目录(通常为C:\bea\weblogic81)
然后在启动脚本startWebLogic.cmd的CLASSPATH的最前面加上ehcache。即将
set CLASSPATH=%WEBLOGIC_CLASSPATH%; %POINTBASE_CLASSPATH%; %JAVA_HOME%\jre\lib\rt.jar; %WL_HOME%\server\lib\webservices.jar; %CLASSPATH%
修改为
set CLASSPATH=%WL_HOME%\commons-logging-1.0.4.jar; %WL_HOME%\backport-util-concurrent-3.1.jar; %WL_HOME%\ehcache-1.4.1.jar; %WEBLOGIC_CLASSPATH%; %POINTBASE_CLASSPATH%; %JAVA_HOME%\jre\lib\rt.jar; %WL_HOME%\server\lib\webservices.jar; %CLASSPATH%
配置好了环境,接下来配置ehcache的配置文件
xsi:noNamespaceSchemaLocation="ehcache.xsd">
class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1, multicastGroupPort=4446" />
class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" />
timeToIdleSeconds="1" timeToLiveSeconds="1" overflowToDisk="false"
memoryStoreEvictionPolicy="LRU" />
overflowToDisk="true" timeToIdleSeconds="60" timeToLiveSeconds="120"
memoryStoreEvictionPolicy="LRU">
class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" />
注意其中的红色字体,每个要使用分布式缓存的cache都必须配置cacheEventListenerFactory。
再接下来就是如何使用ehcache了,下面代码为从一个控制用户同一时间只能有一个session的程序中摘出
static CacheManager manager = new CacheManager(
SingleUserSessionListener.class.getResourceAsStream("/ehcache.xml"));
public static Cache cache = manager.getCache("userCache");
private void removeUser(HttpSessionBindingEvent e) {
if (e.getName().equals("loginUserCode")) {
cache.remove(e.getValue().toString());
}
}
private void checkUser(HttpSessionBindingEvent e) {
if (e.getName().equals("loginUserCode")) {
String userCode = e.getValue().toString();
if (cache.isElementInMemory(userCode)) {
String sid = cache.get(userCode).getValue().toString();
cache.remove(userCode);
System.out.println("踢出用户" + userCode + ",其sessionId=" + sid);
}
Element el = new Element(userCode, e.getSession().getId());
cache.put(el);
}
}