一、前提
在Linux下安装MemCached,并启动服务。
详细请参见:Linux下安装MemCached http://blog.csdn.net/sonnet123/article/details/9133841
二、编写java代码连接MemCached
基于java_memcached-release_2.6.6.zip 中的jar包进行编写java代码连接。
下载链接:https://github.com/gwhalin/Memcached-Java-Client/downloads
1、新建java项目
名称:MemCached
2、添加引用jar包
①右键项目->Build Path->Add External Archives
②选择引用jar包文件:
③添加后如图:
3、编写java类代码
在src下添加Memcache.java 和 MemcacheManager.java类文件
Memcache.java类文件代码:
package com.jjh.common.memcached; import com.danga.MemCached.MemCachedClient; import com.danga.MemCached.SockIOPool; public class Memcache { protected static Memcache mc = new Memcache(); protected MemCachedClient mcc = new MemCachedClient(); static{ //服务器列表和其权重 String[] servers = {"192.168.138.128:12000"}; //String[] servers = {"192.168.71.195:12000"}; Integer[] weights = {3}; //获取sock连接池的实例对象 SockIOPool pool = SockIOPool.getInstance(); //设置服务器信息 pool.setServers(servers); pool.setWeights(weights); //设置初始连接数、最小最大连接数、最大处理时间 pool.setInitConn(5); pool.setMinConn(5); pool.setMaxConn(250); pool.setMaxIdle(1000*60*60*6); //设置主线程的睡眠时间 pool.setMaintSleep(30); pool.setNagle(false); pool.setSocketTO(30); pool.setSocketConnectTO(0); //设置Tcp的参数,连接超时等 pool.initialize(); //压缩设置,超过制定大小(单位K)的数据都会压缩 //mcc.setCompressEnable(false); //mcc.setCompressThreshold(64*1024); } //保护构造函数,不允许实例化 protected Memcache(){} public static Memcache getInstance(){ return mc; } public MemCachedClient getClient(){ return mcc; } }
MemcacheManager.java类文件代码:package com.jjh.common.memcached; import java.util.Date; import com.danga.MemCached.MemCachedClient; public class MemcacheManager { //获取Client方法 public static MemCachedClient getClient(){ return Memcache.getInstance().getClient(); } public static Object get(String key){ return getClient().get(key); } public static boolean set(String key, Object value){ return getClient().set(key, value); } public static boolean set(String key, Object value, long time){ return getClient().set(key, value, new Date(time)); } public static boolean delete(String key){ return getClient().delete(key); } }
4、进行测试
在src下添加MemCachedTest.java类文件
MemCachedTest.java代码如下
右键运行代码,结果输出如下:package com.jjh.common.memcached; public class MemCachedTest { public static void main(String[] args){ String k = "test"; String v = "testMemCached"; System.out.println("-------------------MemCached set begin--------------"); MemcacheManager.set(k, v); System.out.println("setValue:" + v); System.out.println("-------------------MemCached set end--------------"); System.out.println("-------------------MemCached get begin--------------"); String r = (String)MemcacheManager.get(k); System.out.println("getValue:" + r); System.out.println("-------------------MemCached get end--------------"); } }
从以上结果说明:连接成功。