摘要: memcached-java客户端调用get方法获取数据失败
主要演示一下在memcached服务器端set数据之后,在客户端调用java api获取数据。不过此过程如果不慎会读取数据失败。
服务器端添加测试数据
set username 0 0 5 chencanjian STORED get username VALUE username 0 5 chencanjian END
表示在memcached服务器端获取username的值是正常的
memcached客户端代码如下:
package com.memcached.util;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
public class MemcachedUtil { protected static MemCachedClient mcc = new MemCachedClient(); static { String[] servers = {"192.168.0.100:11211"}; Integer[] weights = {3}; // grab an instance of our connection pool SockIOPool pool = SockIOPool.getInstance(); // set the servers and the weights pool.setServers(servers); pool.setWeights(weights); pool.setInitConn( 5 ); pool.setMinConn( 5 ); pool.setMaxConn( 250 ); pool.setMaxIdle( 1000 * 60 * 60 * 6 ); // set the sleep for the maint thread // it will wake up every x seconds and // maintain the pool size pool.setMaintSleep( 30 ); pool.setNagle( false ); pool.setSocketTO( 3000 ); pool.setSocketConnectTO( 0 ); // initialize the connection pool pool.initialize(); } public static void main(String[] args) { System.out.println(mcc.get("username")); } }
执行main方法后,出现了读取异常,异常如下
75 [main] ERROR com.danga.MemCached.MemCachedClient - ++++ exception thrown while trying to get object from cache for key: username 76 [main] ERROR com.danga.MemCached.MemCachedClient - invalid stream header: 6C696C65 java.io.StreamCorruptedException: invalid stream header: 6C696C65 at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:801) at java.io.ObjectInputStream.<init>(ObjectInputStream.java:298)
失败的原因为:
在memcached中,不同的客户端在set或者add值时,对命令的第二个参数的使用是不一致的
<command name> <key> <flags> <exptime> <bytes> <data block> JAVA客户端flags字段填写的都是32,不是32的是无法通过java客户端get出来的 所以在通过memcached服务器端进行数据set时,需要显示指定flags值为32 或者通过java客户端提供的接口set数据