menu

开发进行时...

crazy coder

Avatar

spring中使用Ehcache的事件

这方面的使有的人还真少,网上资料挺少,故分享下

1、Ehcache的事件
Ehcache提供了接口CacheEventListener以支持自定义的事件
事件典型的应用是集群,官方已做了实现
使用起来也很简单:
在配置文件中配置下就OK了。

2、spring way
在spring中提供了Ehcache支持,org.springframework.cache.ehcache.EhCacheFactoryBean

但是这个实现并不支持事件,需要自己扩展

3、代码
自定义事件:

/**
* 配置在ioc容器
* 可注入其它资源
*/
public class PostCounterExpireEvent implements CacheEventListener {
//具体实现的方法略。
//
}


扩展后的CacheFactoryBean:

public class MyCacheFactoryBean extends org.springframework.cache.ehcache.EhCacheFactoryBean {
	private CacheEventListener cacheEventListener;
	public void afterPropertiesSet() throws CacheException, IOException {
		super.afterPropertiesSet();
		Ehcache cache = (Ehcache)super.getObject();
		if(this.cacheEventListener != null)
		cache.getCacheEventNotificationService().registerListener(cacheEventListener);
	}
	public void setCacheEventListener(CacheEventListener cacheEventListener) {
		this.cacheEventListener = cacheEventListener;
	}
}


配置文件:

	<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
		<property name="configLocation">
			<value>classpath:ehcache.xml</value>
		</property>
	</bean>
<!--cacheName:myCache不能在ehcache.xml中定义,否则配置不会生效-->
	<bean id="myCache" class="cache.MyCacheFactoryBean">
		<property name="cacheManager">
			<ref local="cacheManager"/>
		</property>
		<property name="cacheName">
			<value>myCache</value>
		</property>
		<property name="diskExpiryThreadIntervalSeconds" value="3600"/>
		<property name="maxElementsInMemory" value="10000"/>
		<property name="eternal" value="false"/>
		<property name="overflowToDisk" value="true"/>
		<property name="timeToIdle" value="60"/>
		<property name="timeToLive" value="3600"/>
		
		<property name="cacheEventListener">
			<ref local="myExpireEvent"/>
		</property>
	</bean>
<!--很容易使用容器上其它的资源,如持久层-->
	<bean id="myExpireEvent" class="cache.myCacheExpireEvent">
		<property name="someDao">
			<ref bean="someDao"/>
		</property>
	</bean>

评论已关闭