memcached的使用(一)
来源:互联网 发布:mac office 破解补丁 编辑:程序博客网 时间:2024/06/05 16:55
提供一个缓存工具类,在配置文件中配置使用哪种缓存(memcached或ehcached),使其它程序对具体的缓存不依赖,同时使用AOP方式来对方法执行结果进行缓存。
首先是工具类的实现:
在Spring中配置
具体工具类的代码
首先是工具类的实现:
在Spring中配置
代码
在properties文件中配置${cache.servers} ${cache.cacheServerWeights} ${cache.cluster} <!-- EhCache Manager -->
<bean id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation">
<value>classpath:ehcache.xml</value>
</property>
</bean>
<bean id="localCache"
class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager" ref="cacheManager" />
<property name="cacheName"
value="×××.cache.LOCAL_CACHE" />
</bean>
<bean id="cacheService"
class="×××.core.cache.CacheService" init-method="init" destroy-method="destory">
<property name="cacheServerList" value="${cache.servers}"/>
<property name="cacheServerWeights" value="${cache.cacheServerWeights}"/>
<property name="cacheCluster" value="${cache.cluster}"/>
<property name="localCache" ref="localCache"/>
</bean>
<bean id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation">
<value>classpath:ehcache.xml</value>
</property>
</bean>
<bean id="localCache"
class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager" ref="cacheManager" />
<property name="cacheName"
value="×××.cache.LOCAL_CACHE" />
</bean>
<bean id="cacheService"
class="×××.core.cache.CacheService" init-method="init" destroy-method="destory">
<property name="cacheServerList" value="${cache.servers}"/>
<property name="cacheServerWeights" value="${cache.cacheServerWeights}"/>
<property name="cacheCluster" value="${cache.cluster}"/>
<property name="localCache" ref="localCache"/>
</bean>
具体工具类的代码
代码
然后实现函数的AOP拦截类,用来在函数执行前返回缓存内容 public class CacheService ...{
private Log logger = LogFactory.getLog(getClass());
private Cache localCache;
String cacheServerList;
String cacheServerWeights;
boolean cacheCluster = false;
int initialConnections = 10;
int minSpareConnections = 5;
int maxSpareConnections = 50;
long maxIdleTime = 1000 * 60 * 30; // 30 minutes
long maxBusyTime = 1000 * 60 * 5; // 5 minutes
long maintThreadSleep = 1000 * 5; // 5 seconds
int socketTimeOut = 1000 * 3; // 3 seconds to block on reads
int socketConnectTO = 1000 * 3; // 3 seconds to block on initial
// connections. If 0, then will use blocking
// connect (default)
boolean failover = false; // turn off auto-failover in event of server
// down
boolean nagleAlg = false; // turn off Nagle's algorithm on all sockets in
// pool
MemCachedClient mc;
public CacheService()...{
mc = new MemCachedClient();
mc.setCompressEnable(false);
}
/** *//**
* 放入
*
*/
public void put(String key, Object obj) ...{
Assert.hasText(key);
Assert.notNull(obj);
Assert.notNull(localCache);
if (this.cacheCluster) ...{
mc.set(key, obj);
} else ...{
Element element = new Element(key, (Serializable) obj);
localCache.put(element);
}
}
/** *//**
* 删除
*/
public void remove(String key)...{
Assert.hasText(key);
Assert.notNull(localCache);
if (this.cacheCluster) ...{
mc.delete(key);
}else...{
localCache.remove(key);
}
}
/** *//**
* 得到
*/
public Object get(String key) ...{
Assert.hasText(key);
Assert.notNull(localCache);
Object rt = null;
if (this.cacheCluster) ...{
rt = mc.get(key);
} else ...{
Element element = null;
try ...{
element = localCache.get(key);
} catch (CacheException cacheException) ...{
throw new DataRetrievalFailureException("Cache failure: "
+ cacheException.getMessage());
}
if(element != null)
rt = element.getValue();
}
return rt;
}
/** *//**
* 判断是否存在
*
*/
public boolean exist(String key)...{
Assert.hasText(key);
Assert.notNull(localCache);
if (this.cacheCluster) ...{
return mc.keyExists(key);
}else...{
return this.localCache.isKeyInCache(key);
}
}
private void init() ...{
if (this.cacheCluster) ...{
String[] serverlist = cacheServerList.split(",");
Integer[] weights = this.split(cacheServerWeights);
// initialize the pool for memcache servers
SockIOPool pool = SockIOPool.getInstance();
pool.setServers(serverlist);
pool.setWeights(weights);
pool.setInitConn(initialConnections);
pool.setMinConn(minSpareConnections);
pool.setMaxConn(maxSpareConnections);
pool.setMaxIdle(maxIdleTime);
pool.setMaxBusyTime(maxBusyTime);
pool.setMaintSleep(maintThreadSleep);
pool.setSocketTO(socketTimeOut);
pool.setSocketConnectTO(socketConnectTO);
pool.setNagle(nagleAlg);
pool.setHashingAlg(SockIOPool.NEW_COMPAT_HASH);
pool.initialize();
logger.info("初始化memcached pool!");
}
}
private void destory() ...{
if (this.cacheCluster) ...{
SockIOPool.getInstance().shutDown();
}
}
}
private Log logger = LogFactory.getLog(getClass());
private Cache localCache;
String cacheServerList;
String cacheServerWeights;
boolean cacheCluster = false;
int initialConnections = 10;
int minSpareConnections = 5;
int maxSpareConnections = 50;
long maxIdleTime = 1000 * 60 * 30; // 30 minutes
long maxBusyTime = 1000 * 60 * 5; // 5 minutes
long maintThreadSleep = 1000 * 5; // 5 seconds
int socketTimeOut = 1000 * 3; // 3 seconds to block on reads
int socketConnectTO = 1000 * 3; // 3 seconds to block on initial
// connections. If 0, then will use blocking
// connect (default)
boolean failover = false; // turn off auto-failover in event of server
// down
boolean nagleAlg = false; // turn off Nagle's algorithm on all sockets in
// pool
MemCachedClient mc;
public CacheService()...{
mc = new MemCachedClient();
mc.setCompressEnable(false);
}
/** *//**
* 放入
*
*/
public void put(String key, Object obj) ...{
Assert.hasText(key);
Assert.notNull(obj);
Assert.notNull(localCache);
if (this.cacheCluster) ...{
mc.set(key, obj);
} else ...{
Element element = new Element(key, (Serializable) obj);
localCache.put(element);
}
}
/** *//**
* 删除
*/
public void remove(String key)...{
Assert.hasText(key);
Assert.notNull(localCache);
if (this.cacheCluster) ...{
mc.delete(key);
}else...{
localCache.remove(key);
}
}
/** *//**
* 得到
*/
public Object get(String key) ...{
Assert.hasText(key);
Assert.notNull(localCache);
Object rt = null;
if (this.cacheCluster) ...{
rt = mc.get(key);
} else ...{
Element element = null;
try ...{
element = localCache.get(key);
} catch (CacheException cacheException) ...{
throw new DataRetrievalFailureException("Cache failure: "
+ cacheException.getMessage());
}
if(element != null)
rt = element.getValue();
}
return rt;
}
/** *//**
* 判断是否存在
*
*/
public boolean exist(String key)...{
Assert.hasText(key);
Assert.notNull(localCache);
if (this.cacheCluster) ...{
return mc.keyExists(key);
}else...{
return this.localCache.isKeyInCache(key);
}
}
private void init() ...{
if (this.cacheCluster) ...{
String[] serverlist = cacheServerList.split(",");
Integer[] weights = this.split(cacheServerWeights);
// initialize the pool for memcache servers
SockIOPool pool = SockIOPool.getInstance();
pool.setServers(serverlist);
pool.setWeights(weights);
pool.setInitConn(initialConnections);
pool.setMinConn(minSpareConnections);
pool.setMaxConn(maxSpareConnections);
pool.setMaxIdle(maxIdleTime);
pool.setMaxBusyTime(maxBusyTime);
pool.setMaintSleep(maintThreadSleep);
pool.setSocketTO(socketTimeOut);
pool.setSocketConnectTO(socketConnectTO);
pool.setNagle(nagleAlg);
pool.setHashingAlg(SockIOPool.NEW_COMPAT_HASH);
pool.initialize();
logger.info("初始化memcached pool!");
}
}
private void destory() ...{
if (this.cacheCluster) ...{
SockIOPool.getInstance().shutDown();
}
}
}
代码
Spring的AOP配置如下: public class CachingInterceptor implements MethodInterceptor ...{
private CacheService cacheService;
private String cacheKey;
public void setCacheKey(String cacheKey) ...{
this.cacheKey = cacheKey;
}
public void setCacheService(CacheService cacheService) ...{
this.cacheService = cacheService;
}
public Object invoke(MethodInvocation invocation) throws Throwable ...{
Object result = cacheService.get(cacheKey);
//如果函数返回结果不在Cache中,执行函数并将结果放入Cache
if (result == null) ...{
result = invocation.proceed();
cacheService.put(cacheKey,result);
}
return result;
}
}
private CacheService cacheService;
private String cacheKey;
public void setCacheKey(String cacheKey) ...{
this.cacheKey = cacheKey;
}
public void setCacheService(CacheService cacheService) ...{
this.cacheService = cacheService;
}
public Object invoke(MethodInvocation invocation) throws Throwable ...{
Object result = cacheService.get(cacheKey);
//如果函数返回结果不在Cache中,执行函数并将结果放入Cache
if (result == null) ...{
result = invocation.proceed();
cacheService.put(cacheKey,result);
}
return result;
}
}
代码
<aop:config proxy-target-class="true">
<aop:advisor
pointcut="execution(* ×××.PoiService.getOne(..))"
advice-ref="PoiServiceCachingAdvice" />
</aop:config>
<bean id="BasPoiServiceCachingAdvice"
class="×××.core.cache.CachingInterceptor">
<property name="cacheKey" value="PoiService" />
<property name="cacheService" ref="cacheService" />
</bean>
</aop:config>
<aop:advisor
pointcut="execution(* ×××.PoiService.getOne(..))"
advice-ref="PoiServiceCachingAdvice" />
</aop:config>
<bean id="BasPoiServiceCachingAdvice"
class="×××.core.cache.CachingInterceptor">
<property name="cacheKey" value="PoiService" />
<property name="cacheService" ref="cacheService" />
</bean>
</aop:config>
- memcached的使用(一)
- Memcached使用入门(一)
- pomelo下memcached的安装以及使用(一)
- Memcached的.NET客户端(一)【.NET Memcached Client Library使用】
- memcached的基础(一)
- memcached的应用(一)
- Memcached学习一:Memcached安装使用
- Ehcache还是Memcached的抉择(一)
- Redis与Memcached的区别(一)
- Memcached/Libmemcached使用经验总结(一)
- memcached使用总结篇<一>
- memcached之memcached的应用(一)
- memcached之memcached的应用(一)
- memcached 学习(一)
- memcached(一)--安装
- memcached windows下载安装及使用(一)
- 【Memcached】使用一致性哈希实现分布式存储(一)
- Memcached的使用(基于java)
- ubuntu 问题集锦
- C++精华基础贴[水木清华]
- 汇编->字符串比较
- linux as 4+BDB+openldap+phpldapadmin最新版安装方法
- Cisco命令大汇聚---某网络专业人士笔记(超级珍藏)
- memcached的使用(一)
- 如何更好地理解《全程软件测试》
- Get involved in World Wind (Source Code)
- video memory、AGP memory、system memory and write-combing memory
- group by with rollup
- 养胃 - 每天起来一杯水
- 呼叫中心
- 通过ScribeFire离线写CSDN Blog
- 关于DECLARE_MESSAGE_MAP