Memcached通过python为String设置为null,然后从Java获取

当我尝试从我在python中设置的memcached中读取一个String时:

import memcache MC_SERVER = "192.168.1.100" MC_PORT = "11211" mc = memcache.Client(['%s:%s' % (MC_SERVER, MC_PORT)], debug=0) mc.set("test_string", "true") print mc.get("test_string") 

Java告诉我它不存在,当我尝试获取它时显然会返回null:

 import com.danga.MemCached.*; public class Tester { // create a static client as most installs only need // a single instance protected static MemCachedClient mcc = new MemCachedClient(true, false); // set up connection pool once at class load static { // server list and weights String[] servers = { "192.168.1.100:11211" }; // grab an instance of our connection pool SockIOPool pool = SockIOPool.getInstance(); // set the servers and the weights pool.setServers( servers ); // set some TCP settings // disable nagle // set the read timeout to 3 secs // and don't set a connect timeout pool.setNagle( false ); pool.setSocketTO( 3000 ); pool.setSocketConnectTO( 0 ); // initialize the connection pool pool.initialize(); } // from here on down, you can call any of the client calls public static void main(String[] args) { //System.out.println( mcc.set( "test_string", "blah!" ) ); // everything is great is value is set by Java System.out.println( mcc.keyExists( "test_string" ) ); // output is false when value set by python System.out.println( mcc.get( "test_string" ) ); // output is null when value set by python } } 

我猜这与跨语言的对象序列化/非序列化有关但我觉得我可能对简单的字符串很好 – 以前有人遇到过这个问题吗?

这是我正在使用的库:

http://www.tummy.com/Community/software/python-memcached/

http://github.com/gwhalin/Memcached-Java-Client/downloads

解决方案直接来自文档:

如果您需要支持多个客户端(即Java,PHP,Perl等),则需要在设置时进行一些更改:

 // use a compatible hashing algorithm pool.setHashingAlg( SockIOPool.NEW_COMPAT_HASH ); // store primitives as strings // the java client serializes primitives // // note: this will not help you when it comes to // storing non primitives mcc.setPrimitiveAsString( true ); // don't url encode keys // by default the java client url encodes keys // to sanitize them so they will always work on the server // however, other clients do not do this mcc.setSanitizeKeys( false ); 

更改为使用pylibmc来解决它:

 import pylibmc mc = pylibmc.Client(["127.0.0.1"], binary=True, behaviors={"tcp_nodelay": True, "ketama": True}) key="someKey" i=0 while True: #mc.set(key, str(i)) value = mc.get(key) print(value) sleep(1) i+=1 

Java不使用unicode吗? 如果是这样,我怀疑python正在使用ASCII / latin 1字符集写入memcache。 结果,键看起来非常不同(“test_string”与“t \ 00e \ 00s \ 00t \ 00_ \ 00s \ 00t \ 00r \ 00i \ 00n \ 00g \ 00”)。

尝试使用它,看看会发生什么。

 import memcache MC_SERVER = "192.168.1.100" MC_PORT = "11211" mc = memcache.Client(['%s:%s' % (MC_SERVER, MC_PORT)], debug=0) mc.set(u"test_string", u"true") print mc.get(u"test_string") 

确保已启动memcached服务,如果已启动,则重新启动该服务。

它是Java客户端中的错误。 您应该获得带有修复程序的分叉项目: https : //github.com/zmokhtar/Memcached-Java-Client

编辑

我可以用gwhalin / Memcached-Java-Client重现问题,但zmokhtar / Memcached-Java-Client一切都很好