Memcached-Java-Client是Memcached官方提供的Java语言访问Memcached的client,使用它可以比较方便地与缓存服务端进行通信。
下载地址:https://github.com/gwhalin/Memcached-Java-Client/downloads,
下载最新版本 java_memcached-release_2.6.6.zip
memcached 是多线程 默认端口 11211
redis是单线程 端口 6379
java代码如下:
package memcache; import java.io.Serializable; import java.util.Date; import com.danga.MemCached.MemCachedClient; import com.danga.MemCached.SockIOPool; class User implements Serializable{ //必须将对象序列化才能保存 public String userName; public String password; } public class MemcacheManagerForGwhalin { // 构建缓存客户端 private static MemCachedClient cachedClient; // 单例模式实现客户端管理类 private static MemcacheManagerForGwhalin INSTANCE = new MemcacheManagerForGwhalin(); private MemcacheManagerForGwhalin() { cachedClient = new MemCachedClient(); //获取连接池实例 SockIOPool pool = SockIOPool.getInstance(); //设置缓存服务器地址,可以设置多个实现分布式缓存 pool.setServers(new String[]{"127.0.0.1:11211"}); //设置初始连接5 pool.setInitConn(5); //设置最小连接5 pool.setMinConn(5); //设置最大连接250 pool.setMaxConn(250); //设置每个连接最大空闲时间3个小时 pool.setMaxIdle(1000 * 60 * 60 * 3); pool.setMaintSleep(30); pool.setNagle(false); pool.setSocketTO(3000); pool.setSocketConnectTO(0); pool.initialize(); } /** * * * 获取缓存管理器唯一实例 * @return */ public static MemcacheManagerForGwhalin getInstance() { return INSTANCE; } public void add(String key, Object value) { cachedClient.set(key, value); } public void add(String key, Object value, int milliseconds) { cachedClient.set(key, value, milliseconds); } public void remove(String key) { cachedClient.delete(key); } public void remove(String key, int milliseconds) { cachedClient.delete(key, milliseconds, new Date()); } public void update(String key, Object value, int milliseconds) { cachedClient.replace(key, value, milliseconds); } public void update(String key, Object value) { cachedClient.replace(key, value); } public Object get(String key) { return cachedClient.get(key); } public static void main(String args[]){ MemcacheManagerForGwhalin memcache = MemcacheManagerForGwhalin.getInstance(); memcache.add("4", new User()); System.out.println(memcache.get("4")); } }
×××请见附件
参考文章:
http://asher.blog.163.com/blog/static/174174566201321421241578/
与Spring集成
http://blog.csdn.net/dhdhdh0920/article/details/42242521