memcached 安装什么的就不再说了,网上太多了。
客户端,我选择的是Java Memcached Client,新版本修复了很多问题,而且稳定性上高于其他版本。
下面就是系统配置,加入Memcached 引用:
<bean class="com.danga.MemCached.SockIOPool" destroy-method="shutDown" factory-method="getInstance" id="memcachedPool" init-method="initialize"> <constructor-arg> <value>neeaMemcachedPool</value> </constructor-arg> <property name="servers"> <list> <value>127.0.0.1:12345</value> </list> </property> <property name="initConn"> <value>10</value> </property> <property name="minConn"> <value>5</value> </property> <property name="maxConn"> <value>100</value> </property> <property name="maintSleep"> <value>3000</value> </property> <property name="nagle"> <value>false</value> </property> <property name="socketTO"> <value>3000</value> </property> </bean> <bean class="com.danga.MemCached.MemCachedClient"> <constructor-arg> <value>neeaMemcachedPool</value> </constructor-arg> </bean>
实现整合的类,主要是利用Spring Aop的环绕通知来实现无入侵式的整合,代码如下:
public class MemcachedIntegrated { @Autowired private MemCachedClient mcc; private static Log log = LogFactory.getLog(MemcachedIntegrated.class); public Object doAround(ProceedingJoinPoint jp) { Object result = null; String key = ""; StringBuffer sb = new StringBuffer(); sb.append(jp.getSignature().getName()); //Key的规则这块,还不完善,如果查询参数传入的是一个对象的时候,就没用了 for (Object obj : jp.getArgs()) { if (obj !=null) sb.append(obj); } key = sb.toString().replace(" ", ""); result = mcc.get(key); log.info(key); if (result != null) { log.info("Get cached object:" + key); return result; } try { result = jp.proceed(jp.getArgs()); } catch (Throwable e) { } if (result !=null) mcc.set(key, result, 3600); return result; } }
配置AOP:
<bean id="memcachedIntegrated" class="com.××××.dao.ibatis.MemcachedIntegrated"/> <aop:config> <aop:aspect id="TestAspect" ref="memcachedIntegrated"> <!--配置com.×××.dao.ibatis包下所有已get开头的方法--> <aop:pointcut id="daoIntegarte" expression="execution(* com.××××.dao.ibatis.*.get*(..))" /> <aop:around pointcut-ref="daoIntegarte" method="doAround"/> </aop:aspect> </aop:config>
通过以上配置就完成集成Memcached。
接下来继续集成memcached后,如果有做更新、删除、新增操作时,如何更新缓存。