Memcached Java Client Spring整合
如果你的项目是使用Spring作为中间件的,那么Spring的整合配置是很有用的。
配置文件
applicationContext-memcachedjavaclient.xml
neeaMemcachedPool
localhost:11211 localhost:11212 localhost:11213 5 5 250 30 false 6000 3000 neeaMemcachedPool
业务代码
对原来直接使用JVM容器的代码进行微调,服务方法中修改调用单例获取memcached客户端实例为依赖Spring注入。
服务接口类:MemcachedClientService/** * Memcached 常用功能接口定义,用于业务层直接使用,屏蔽各种客户端实现的API差异,实现解耦客户端与业务系统的目的 * 无过期时间和flags支持,无append,prepend,replace,incr,decr等操作 * * @author zhangpu * */public interface MemcachedClientService { String get(String key); CacheItem gets(String key); boolean add(String key, String value); boolean set(String key, String value); boolean cas(String key, String value, long unique); boolean delete(String key); boolean flushAll();}
服务实现类:MemcachedClientServiceJavaClientImpl
/** * Memcached for java 客户端缓存服务实现 (SPING) * * @author zhangpu * */public class MemcachedClientServiceJavaClientImpl implements MemcachedClientService { /** 客户端实现注入 */ private MemCachedClient memCachedClient; public void setMemCachedClient(MemCachedClient memCachedClient) { this.memCachedClient = memCachedClient; } public boolean add(String key, String value) { return memCachedClient.add(key, value); } public boolean cas(String key, String value, long unique) { return memCachedClient.cas(key, value, unique); } public String get(String key) { return (String) memCachedClient.get(key); } public CacheItem gets(String key) { MemcachedItem item = memCachedClient.gets(key); return new CacheItem(key, (String) item.getValue(), item.getCasUnique()); } public boolean set(String key, String value) { return memCachedClient.set(key, value); } public boolean delete(String key) { return memCachedClient.delete(key); } public boolean flushAll() { return memCachedClient.flushAll(); }}
代码验证
public class MemcachedClientSerivceSpringTest { public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "applicationContext-memcachedjavaclient.xml" }); MemcachedClientService memcachedClientService = (MemcachedClientService) context .getBean("memcachedClientService"); String key = "keySpring"; String value = "i like Spring."; String newValue = "i love Spring"; System.out.println("add: " + memcachedClientService.add(key, value)); System.out.println("set: " + memcachedClientService.set(key, newValue)); System.out.println("get: " + memcachedClientService.get(key)); CacheItem item = memcachedClientService.gets(key); System.out.println("gets: " + item); System.out.println("cas: " + memcachedClientService.cas(key, newValue, item.getUnique())); System.out.println("del: " + memcachedClientService.delete(key)); }}
执行结果:
add: trueset: trueget: i love Springgets: {key:keySpring,value:i love Spring,unique:2701285}cas: truedel: true
配置问题
配置文件中,我注释了权重配置,是因为SocketPool中的权重参数是Integer[],我没有想到办法怎么在Spring配置中注入Integer[]参数,以前都是自己的代码,可以转换为字符串跳过此问题了。
1,1,1
解决办法:
- 扩展Spring的配置实现,Spring提供了相关扩展方法,支持自定义参数配置。
- 下载memcached java client的源代码,修改下SocketPool的实现。