1.memcached服务协议
2.memCached协议基本操作
1)存储命令 set 数据块 add replace 完整的存储命令:其中\r\n是回车换行\r\n \r\n 样例: set user 0 180 5 huang STORED get user VALUE user 0 5 huang END 2)读取命令 get 关键字 3)其他命令 flush_all version stats
3. 下载Java MemCached客户端,解压缩后将所有jar文件拷贝到java工程的lib目录下或者classpath目录下
4.编写Java访问memcached服务端的代码
package hxb.memcached;import com.danga.MemCached.MemCachedClient;import com.danga.MemCached.SockIOPool;public class KypuloCachedManager { private static KypuloCachedManager cachedManager ; //MemCached客户端类 private MemCachedClient memCachedClient = new MemCachedClient(); //MemCached服务端节点,在分布式环境中包含了多个server private String[] memCachedServers = {"192.168.146.128:11211"}; //各服务端节点负载均衡权重数 private Integer[] weights ={3}; private KypuloCachedManager() { initCachedPool(); } private void initCachedPool() { SockIOPool pool = SockIOPool.getInstance(); pool.setServers(memCachedServers); pool.setWeights(weights); // 设置初始连接数、最小和最大连接数以及最大处理时间 pool.setInitConn( 5 ); pool.setMinConn( 5 ); pool.setMaxConn( 250 ); pool.setMaxIdle( 1000 * 60 * 60 * 6 ); // 设置主线程的睡眠时间 pool.setMaintSleep( 30 ); // 设置TCP的参数,连接超时等 pool.setNagle( false ); pool.setSocketTO( 3000 ); pool.setSocketConnectTO( 0 ); // 初始化连接池 pool.initialize(); } public synchronized static KypuloCachedManager getInstance() { if(cachedManager==null) { cachedManager= new KypuloCachedManager(); } return cachedManager; } /** * 缓存一个对象 * @param key 对象关键字 * @param value 需要存储的对象 * @return 缓存成功返回true 失败返回false */ public boolean add(String key, Object value) { return this.memCachedClient.add(key, value); } /** * 更新缓存中的一个对象 * @param key 对象关键字 * @param value 刷新的的对象 * @return */ public boolean update(String key , Object value) { return this.memCachedClient.replace(key, value); } /** * 获取缓存中指定关键字的对象 * @param key 对象关键字 * @return 缓存的对象 */ public Object get(String key) { return this.memCachedClient.get(key); } public static void main(String[] args) { KypuloCachedManager cachedManagerInstance = KypuloCachedManager.getInstance(); cachedManagerInstance.add("username", "Kypulo"); System.out.println("Get username from cached:"+cachedManagerInstance.get("username")); cachedManagerInstance.update("username", "Huangxiaobing"); System.out.println("Get username from cached after update:"+cachedManagerInstance.get("username")); }}