介绍

Memcached java client是官方推荐的最早的memcached java客户端。最新版本:java_memcached-release_2.6.1。

官方下载地址:https://github.com/gwhalin/Memcached-Java-Client

采用阻塞式SOCKET通讯,据说目前版本进行了很多优化,性能有所提高(只看过1.5的源代码,还没来及看最新的)
提供key方式的连接池,默认连接池key为default。(老版本了)。2.6.1版本支持apache-commoms-pool作为连接池。
支持权重配置。
后期的版本提增加了cas支持和getMutl功能

官方示例代码

Java代码  
  1. import com.danga.MemCached.MemCachedClient;
  2. import com.danga.MemCached.SockIOPool;
  3. import com.schooner.MemCached.MemcachedItem;
  4. public class MemcachedForJavaExample {
  5. // create a static client as most installs only need
  6. // a single instance
  7. protected static MemCachedClient mcc = new MemCachedClient();
  8. // set up connection pool once at class load
  9. static {
  10. // server list and weights
  11. String[] servers = { "localhost:11211", "localhost:11212", "localhost:11213" };
  12. Integer[] weights = { 3, 3, 2 };
  13. // grab an instance of our connection pool
  14. SockIOPool pool = SockIOPool.getInstance();
  15. // set the servers and the weights
  16. pool.setServers(servers);
  17. pool.setWeights(weights);
  18. pool.setHashingAlg(SockIOPool.CONSISTENT_HASH);
  19. // set some basic pool settings
  20. // 5 initial, 5 min, and 250 max conns
  21. // and set the max idle time for a conn
  22. // to 6 hours
  23. pool.setInitConn(5);
  24. pool.setMinConn(5);
  25. pool.setMaxConn(250);
  26. pool.setMaxIdle(1000 * 60 * 60 * 6);
  27. // set the sleep for the maint thread
  28. // it will wake up every x seconds and
  29. // maintain the pool size
  30. pool.setMaintSleep(30);
  31. // set some TCP settings
  32. // disable nagle
  33. // set the read timeout to 3 secs
  34. // and don't set a connect timeout
  35. pool.setNagle(false);
  36. pool.setSocketTO(3000);
  37. pool.setSocketConnectTO(0);
  38. // initialize the connection pool
  39. pool.initialize();
  40. }
  41. public static void main(String[] args) {
  42. System.out.println("SET: " + mcc.set("key1", "value1"));
  43. System.out.println("SET: " + mcc.set("key2", "value2"));
  44. System.out.println("SET: " + mcc.set("key3", "value3"));
  45. System.out.println("GET: " + mcc.get("key1"));
  46. MemcachedItem item = mcc.gets("key1");
  47. System.out.println("GETS: value=" + item.getValue() + ",CasUnique:"+item.getCasUnique());
  48. System.out.println("SET: " + mcc.set("key1", "value1_1"));
  49. System.out.println("CAS: " + mcc.cas("key1", "value1_2", item.getCasUnique())); //必须FALSE
  50. System.out.println("getMulti:" + mcc.getMulti(new String[]{"key1","key2","key3"}));
  51. }
  52. }
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
import com.schooner.MemCached.MemcachedItem;public class MemcachedForJavaExample {// create a static client as most installs only need// a single instanceprotected static MemCachedClient mcc = new MemCachedClient();// set up connection pool once at class loadstatic {// server list and weightsString[] servers = { "localhost:11211", "localhost:11212", "localhost:11213" };Integer[] weights = { 3, 3, 2 };// grab an instance of our connection poolSockIOPool pool = SockIOPool.getInstance();// set the servers and the weightspool.setServers(servers);pool.setWeights(weights);pool.setHashingAlg(SockIOPool.CONSISTENT_HASH);// set some basic pool settings// 5 initial, 5 min, and 250 max conns// and set the max idle time for a conn// to 6 hourspool.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 sizepool.setMaintSleep(30);// set some TCP settings// disable nagle// set the read timeout to 3 secs// and don't set a connect timeoutpool.setNagle(false);pool.setSocketTO(3000);pool.setSocketConnectTO(0);// initialize the connection poolpool.initialize();}public static void main(String[] args) {System.out.println("SET: " + mcc.set("key1", "value1"));System.out.println("SET: " + mcc.set("key2", "value2"));System.out.println("SET: " + mcc.set("key3", "value3"));System.out.println("GET: " + mcc.get("key1"));MemcachedItem item = mcc.gets("key1");System.out.println("GETS: value=" + item.getValue() + ",CasUnique:"+item.getCasUnique());System.out.println("SET: " + mcc.set("key1", "value1_1"));System.out.println("CAS: " + mcc.cas("key1", "value1_2", item.getCasUnique())); //必须FALSESystem.out.println("getMulti:" + mcc.getMulti(new String[]{"key1","key2","key3"}));}}

我的代码

这个标题不好取,因为是我自己的想法,还需要大家多提意见,一起讨论。想叫“建议代码”或者“推荐代码”,觉得不合适,还是先叫“我的代码”吧,呵呵。

我的思路

1. 在原始客户端上层,根据业务需求封装MemcachedService(或叫MemcachedClient),负责缓存功能的包装。如:你的业务只需要add,set,get,gets,cas,delete业务,那就只封装这几个功能。这样做的好处是,屏蔽了各种客户端的API差异,让你的业务系统与客户端实现解耦合,如果你以后需要换客户端实现,对你的业务系统不会照成影响。
2.  一般不要直接采用new的方式在你的代码中显示使用memcached客户端实现,应该采用单例的方式使用memcached客户端实现,或者使用Spring的singleton方式配置。Memcached客户端实现是线程安全的。
3. memcached客户端一般都需要大量的配置,考虑扩展和配置修改,应该把参数设置设计为可配置的,可以写到propertis配置文件中或是使用Spring进行配置。

我的实现

业务层封装接口

Java代码  
  1. /**
  2. * Memcached 常用功能接口定义,用于业务层直接使用,屏蔽各种客户端实现的API差异,实现解耦客户端与业务系统的目的
  3. * 无过期时间和flags支持,无append,prepend,replace,incr,decr等操作
  4. *
  5. * @author zhangpu
  6. *
  7. */
  8. public interface MemcachedClientService {
  9. String get(String key);
  10. CacheItem gets(String key);
  11. boolean add(String key, String value);
  12. boolean set(String key, String value);
  13. boolean cas(String key, String value, long unique);
  14. boolean delete(String key)
  15. boolean flushAll();
  16. }
/*** Memcached 常用功能接口定义,用于业务层直接使用,屏蔽各种客户端实现的API差异,实现解耦客户端与业务系统的目的* 无过期时间和flags支持,无append,prepend,replace,incr,decr等操作* * @author zhangpu* */
public interface MemcachedClientService {String get(String key);CacheItem gets(String key);boolean add(String key, String value);boolean set(String key, String value);boolean cas(String key, String value, long unique);boolean delete(String key)boolean flushAll();}
Java代码  
  1. public class CacheItem {
  2. private String key;
  3. private String value;
  4. private long unique;
  5. public CacheItem() {
  6. super();
  7. }
  8. public CacheItem(String key, String value, long unique) {
  9. super();
  10. this.key = key;
  11. this.value = value;
  12. this.unique = unique;
  13. }
  14. public String getKey() {
  15. return key;
  16. }
  17. public void setKey(String key) {
  18. this.key = key;
  19. }
  20. public String getValue() {
  21. return value;
  22. }
  23. public void setValue(String value) {
  24. this.value = value;
  25. }
  26. public long getUnique() {
  27. return unique;
  28. }
  29. public void setUnique(long unique) {
  30. this.unique = unique;
  31. }
  32. }
public class CacheItem {private String key;private String value;private long unique;public CacheItem() {super();}public CacheItem(String key, String value, long unique) {super();this.key = key;this.value = value;this.unique = unique;}public String getKey() {return key;}public void setKey(String key) {this.key = key;}public String getValue() {return value;}public void setValue(String value) {this.value = value;}public long getUnique() {return unique;}public void setUnique(long unique) {this.unique = unique;}}

客户端缓存服务实现

Java代码  
  1. /**
  2. * Memcached for java客户端缓存服务实现
  3. * @author zhangpu
  4. *
  5. */
  6. public class MemcachedClientJava implements MemcachedClientService {
  7. MemCachedClient mmc = MemcachedClientFactory.getInstance();
  8. public boolean add(String key, String value) {
  9. return mmc.add(key, value);
  10. }
  11. public boolean cas(String key, String value, long unique) {
  12. return mmc.cas(key, value, unique);
  13. }
  14. public String get(String key) {
  15. return (String) mmc.get(key);
  16. }
  17. public CacheItem gets(String key) {
  18. MemcachedItem item = mmc.gets(key);
  19. return new CacheItem(key, (String) item.getValue(), item.getCasUnique());
  20. }
  21. public boolean set(String key, String value) {
  22. return mmc.set(key, value);
  23. }
  24. public boolean delete(String key) {
  25. return mmc.delete(key);
  26. }
  27. public boolean flushAll() {
  28. return mmc.flushAll();
  29. }
  30. }
/*** Memcached for java客户端缓存服务实现* @author zhangpu**/
public class MemcachedClientJava implements MemcachedClientService {MemCachedClient mmc = MemcachedClientFactory.getInstance();public boolean add(String key, String value) {return mmc.add(key, value);}public boolean cas(String key, String value, long unique) {return mmc.cas(key, value, unique);}public String get(String key) {return (String) mmc.get(key);}public CacheItem gets(String key) {MemcachedItem item = mmc.gets(key);return new CacheItem(key, (String) item.getValue(), item.getCasUnique());}public boolean set(String key, String value) {return mmc.set(key, value);}public boolean delete(String key) {return mmc.delete(key);}public boolean flushAll() {return mmc.flushAll();}}

获取客户端实例

Java代码  
  1. /**
  2. * MemcachedClient 单例(JDK1.5以上)
  3. * @author zhangpu
  4. *
  5. */
  6. public class MemcachedClientFactory extends ConfigurableConstants{
  7. private static volatile MemCachedClient mmc;
  8. static {
  9. init("memcached-client.properties");
  10. //{ "localhost:11211", "localhost:11212", "localhost:11213" };
  11. String[] servers = getProperty("memcached-servers","").split(",");
  12. Integer[] weights = null;
  13. String weightsCfg = getProperty("memcached-weights","");
  14. if(weightsCfg != null){
  15. String[] wcfg = weightsCfg.split(",");
  16. weights = new Integer[wcfg.length];
  17. for (int i = 0; i < weights.length; i++) {
  18. weights[i] = Integer.valueOf(wcfg[i]);
  19. }
  20. }else{
  21. weights = new Integer[servers.length];
  22. for (int i = 0; i < weights.length; i++) {
  23. weights[i] = 1;
  24. }
  25. }
  26. SockIOPool pool = SockIOPool.getInstance();
  27. pool.setServers(servers);
  28. pool.setWeights(weights);
  29. pool.setHashingAlg(SockIOPool.CONSISTENT_HASH);
  30. pool.setInitConn(getProperty("memcached-initConn",5));
  31. pool.setMinConn(getProperty("memcached-minConn",5));
  32. pool.setMaxConn(getProperty("memcached-maxConn",250));
  33. pool.setMaxIdle(1000 * 60 * 60 * 6);
  34. pool.setMaintSleep(30);
  35. pool.setNagle(false);
  36. pool.setSocketTO(3000);
  37. pool.setSocketConnectTO(0);
  38. pool.initialize();
  39. }
  40. private MemcachedClientFactory() {
  41. }
  42. public static MemCachedClient getInstance() {
  43. if (mmc == null) {
  44. synchronized (MemCachedClient.class) {
  45. if (mmc == null) {
  46. mmc = new MemCachedClient();
  47. }
  48. }
  49. }
  50. return mmc;
  51. }
  52. }
/*** MemcachedClient 单例(JDK1.5以上)* @author zhangpu**/
public class MemcachedClientFactory extends ConfigurableConstants{private static volatile MemCachedClient mmc;static {init("memcached-client.properties");//{ "localhost:11211", "localhost:11212", "localhost:11213" };String[] servers = getProperty("memcached-servers","").split(",");Integer[] weights = null;String weightsCfg = getProperty("memcached-weights","");if(weightsCfg != null){String[] wcfg = weightsCfg.split(",");weights = new Integer[wcfg.length];for (int i = 0; i < weights.length; i++) {weights[i] = Integer.valueOf(wcfg[i]);}}else{weights = new Integer[servers.length];for (int i = 0; i < weights.length; i++) {weights[i] = 1;}}SockIOPool pool = SockIOPool.getInstance();pool.setServers(servers);pool.setWeights(weights);pool.setHashingAlg(SockIOPool.CONSISTENT_HASH);pool.setInitConn(getProperty("memcached-initConn",5));pool.setMinConn(getProperty("memcached-minConn",5));pool.setMaxConn(getProperty("memcached-maxConn",250));pool.setMaxIdle(1000 * 60 * 60 * 6);pool.setMaintSleep(30);pool.setNagle(false);pool.setSocketTO(3000);pool.setSocketConnectTO(0);pool.initialize();}private MemcachedClientFactory() {}public static MemCachedClient getInstance() {if (mmc == null) {synchronized (MemCachedClient.class) {if (mmc == null) {mmc = new MemCachedClient();}}}return mmc;}}

参数配置

Java代码  
  1. /**
  2. * 通过 properties 文件配置设置常量基类 负责加载和读取 properties 属性文件并提供访问的静态工具方法
  3. *
  4. * @author zhangpu
  5. *
  6. */
  7. public class ConfigurableConstants {
  8. protected static Log logger = LogFactory.getLog(ConfigurableConstants.class);
  9. protected static Properties p = new Properties();
  10. protected static void init(String propertyFileName) {
  11. InputStream in = null;
  12. try {
  13. in = ConfigurableConstants.class.getClassLoader().getResourceAsStream(propertyFileName);
  14. if (in != null)
  15. p.load(in);
  16. } catch (IOException e) {
  17. logger.error("load " + propertyFileName + " into Constants error!");
  18. } finally {
  19. if (in != null) {
  20. try {
  21. in.close();
  22. } catch (IOException e) {
  23. logger.error("close " + propertyFileName + " error!");
  24. }
  25. }
  26. }
  27. }
  28. protected static String getProperty(String key, String defaultValue) {
  29. return p.getProperty(key, defaultValue);
  30. }
  31. protected static int getProperty(String key, int defaultValue) {
  32. try {
  33. return Integer.parseInt(getProperty(key, ""));
  34. } catch (Exception e) {
  35. return defaultValue;
  36. }
  37. }
  38. }
/*** 通过 properties 文件配置设置常量基类 负责加载和读取 properties 属性文件并提供访问的静态工具方法** @author zhangpu**/public class ConfigurableConstants {protected static Log logger = LogFactory.getLog(ConfigurableConstants.class);protected static Properties p = new Properties();protected static void init(String propertyFileName) {InputStream in = null;try {in = ConfigurableConstants.class.getClassLoader().getResourceAsStream(propertyFileName);if (in != null)p.load(in);} catch (IOException e) {logger.error("load " + propertyFileName + " into Constants error!");} finally {if (in != null) {try {in.close();} catch (IOException e) {logger.error("close " + propertyFileName + " error!");}}}}protected static String getProperty(String key, String defaultValue) {return p.getProperty(key, defaultValue);}protected static int getProperty(String key, int defaultValue) {try {return Integer.parseInt(getProperty(key, ""));} catch (Exception e) {return defaultValue;}}}

配置文件

memcached-client.properties

Properties代码  
  1. memcached-client.properties
  2. memcached-servers=localhost:11211,localhost:11212,localhost:11213
  3. memcached-weights=3,3,2
  4. memcached-initConn=5
  5. memcached-minConn=5
  6. memcached-maxConn=250
memcached-client.properties
memcached-servers=localhost:11211,localhost:11212,localhost:11213
memcached-weights=3,3,2
memcached-initConn=5
memcached-minConn=5
memcached-maxConn=250

后续提供性能测试,spring整合,版本差异测试,及其它客户端对比。

Memcached学习笔记 — 第四部分:Memcached Java 客户端-gwhalin(1)-介绍及使用相关推荐

  1. MongoDB学习笔记(四)使用Java进行实时监控与数据收集(空间使用量、连接数)

    目录: MongoDB学习笔记(一)环境搭建与常用操作 MongoDB学习笔记(二)使用Java操作MongoDB MongoDB学习笔记(三)使用Spring Data操作MongoDB Mongo ...

  2. memcached学习笔记(1)——memcached原理

    1.memcached简介 memcached是以LiveJournal旗下Danga Interactive公司的Brad Fitzpatric为首开发的一款软件.现在已成为mixi.hatena. ...

  3. Java8实战学习笔记(四)——高效 Java 8 编程(一)

    一.重构.测试和调试 (一).为改善可读性和灵活性重构代码 用更紧凑的方式描述程序的行为 -- Lambda表达式 将一个既有的方法作为参数传递给另一个方法 -- 方法引用 如何运用前几章介绍的Lam ...

  4. Effective Java(第三版) 学习笔记 - 第四章 类和接口 Rule20~Rule25

    Effective Java(第三版) 学习笔记 - 第四章 类和接口 Rule20~Rule25 目录 Rule20 接口优于抽象类 Rule21 为后代设计接口 Rule22 接口只用于定义类型 ...

  5. Java学习笔记(四)——接口

    Java学习笔记(四)--接口 1.格式 2.接口的特点 3.接口举例 1.格式 接口:初期理解,可以认为是一个特殊的抽象类.当抽象类中的方法都是抽象的,那么该类 可以通过接口的方式来表示. clas ...

  6. JVM学习笔记(四)

    JVM学习笔记(四) 文章目录 JVM学习笔记(四) 笔记链接 1.GC算法 1.1GC-判断对象是否可回收 1.1.1 引用计数法 1.1.1 可达性分析 1.2GC-回收算法 标记清除法(Mark ...

  7. python3笔记_Python3学习笔记(四)

    原标题:Python3学习笔记(四) 错误.调试和测试 程序运行中,可能会遇到BUG.用户输入异常数据以及其它环境的异常,这些都需要程序猿进行处理.Python提供了一套内置的异常处理机制,供程序猿使 ...

  8. Android学习笔记(四):在Activity中跳转--Intent的使用

    Android学习笔记(四):在Activity中跳转--Intent的使用 上篇,我们实战了一个很小的项目BMI,通过BMI这个项目,可以很好的理解Activity的程序结构,以方便后面高级API的 ...

  9. Docker 学习笔记 - 进阶四 Docker网络和 Docker compose

    Docker 学习笔记 - 进阶四 Docker网络和 Docker compose 4. docker 网络 4.1 docker network是什么 4.1.1 docker不启动,默认网络情况 ...

最新文章

  1. 有序标称变量(Categorical Features)编码为数值变量(Continuous Features​​​​​​​)详解及实践
  2. Windows注册表修改实例完全手册(上)
  3. python3高级语法:__slots__属性、property装饰器、上下文管理协议、__new__方法
  4. spring知识概要
  5. matlab绘制csv图片,Matlab处理csv文件与图形绘制总结
  6. 当执行打印预览window.close无效
  7. Nacos源码BeatReactor
  8. IIS支持Shtml后辍文件方法
  9. C++ 虚函数重载多态
  10. vscode 插件推荐 - 献给所有前端工程师(2018.4.29更新)
  11. 【CSS】text-align:justify 的使用
  12. Linux内核4.17再获捷报
  13. 计算机二级方案管理器,计算机二级考试真题-Word-学生成绩管理系统需求分析
  14. linux服务器硬盘检测,Linux服务器硬盘坏道检测
  15. javascript封装滑块
  16. 名帖234 俞和 行书《云锦帖》
  17. python谷歌小恐龙,这还是你断网时的样子嘛~
  18. 我们可以用什么来编辑html文件,编辑HTML文件要用什么软件?
  19. 【mysql】 踩坑记录之derived(派生表)
  20. GC_CONCURRENT freed 循环不停打印日志

热门文章

  1. pyqt5讲解10:布局管理讲解大全
  2. opencv进阶学习笔记13:图像形态学操作大全(膨胀,腐蚀,开闭,黑帽,顶帽,梯度)python版
  3. wxWidgets:Sizer 概览
  4. boost::copy_n相关的测试程序
  5. boost::mp11::mp_similar相关用法的测试程序
  6. boost::locale::generator用法的测试程序
  7. boost::histogram::make_weighted_histogram用法的测试程序
  8. boost::fusion::zip_view用法的测试程序
  9. boost::format模块测试构造对象和基本解析
  10. boost::filesystem::detail::possible_large_file_size_support