1. 背景:
php 使用memcached客户端设置一个key,java使用java-memcached-client去读,报错如下:
ERROR|com.whalin.MemCached.MemCachedClient:-1|++++ exception thrown while trying to get object from cache for key: glt7hpcdi1ggo03l9qknu8a755
2. 网上搜索,发现最多的解释:
4.0. 增加spymemcached依赖
4.1. 配置memcached的ip地址
分别在dev,test,idc,prod的app-config.properties文件下添加memcached的ip地址:
dev,test:memcache_ip=192.168.1.10:11211
idc:memcache_ip=172.16.4.10:11211
prod:memcache_ip=172.16.0.10:11211
4.2. 配置memcached实例:
app-cached.xml文件增加:
4.3. 新增类SpringContextHolder
import java.util.Map;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;/** * * 以静态变量保存Spring ApplicationContext,可在任何代码任何地方任何时候中取出ApplicaitonContext. **/public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; /** * * 实现ApplicationContextAware接口的context注入函数,将其存入静态变量. */ public void setApplicationContext(ApplicationContext applicationContext) { SpringContextHolder.applicationContext = applicationContext; } /** * * 取得存储在静态变量中的ApplicationContext. */ public static ApplicationContext getApplicationContext() { checkApplicationContext(); return applicationContext; } /** * * 从静态变量ApplicationContext中取得Bean,自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static
4.4.增加MemcacheUtil
import com.test.bean.SpringContextHolder;import net.spy.memcached.MemcachedClient;public class MemcacheUtil { public static MemcachedClient getMemCachedClient() { return SpringContextHolder.getBean("memcachedClient");}}
4.5 测试代码
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "classpath:spring-memcached-spy.xml"); MemcachedClient client=MemcacheUtil.getMemCachedClient(); //MemcachedClient client =(MemcachedClient)context.getBean("memcachedClient"); Object obj=client.get("glt7hpcdi1ggo03l9qknu8a755"); System.out.println(obj); }
注意事项:
使用spy memcached客户端,在key-value对中,如果value是对象的话,则读取不到,是string的话则可以读取。故建议使用时key-value约定为string类型。value为对象的话,可以考虑转成json串。