Java操作Memcached

转自:http://blog.csdn.net/gaohuanjie/article/details/41913017

        总结一下如何使用Java操作Memcached:

        代码一:

  1. package com.ghj.packageoftool;  
  2.   
  3. import java.io.BufferedWriter;  
  4. import java.io.FileWriter;  
  5. import java.io.IOException;  
  6. import java.io.PrintWriter;  
  7. import java.io.StringWriter;  
  8. import java.lang.management.ManagementFactory;  
  9. import java.text.SimpleDateFormat;  
  10. import java.util.Date;  
  11.   
  12. import com.danga.MemCached.MemCachedClient;  
  13. import com.danga.MemCached.SockIOPool;  
  14.   
  15. /** 
  16.  * Memcached工具类 
  17.  *  
  18.  * @author GaoHuanjie 
  19.  */  
  20. public class MemcachedUtils {  
  21.   
  22.     private static MemCachedClient memCachedClient;  
  23.     static {  
  24.          /************************************配置Memcached**************************************/  
  25.          SockIOPool sockIOPool = SockIOPool.getInstance();  
  26.   
  27.          sockIOPool.setServers(new String[]{“127.0.0.1:11211”});//设置memcached服务器地址  
  28.          sockIOPool.setWeights(new Integer[]{3});               //设置每个MemCached服务器权重   
  29.          sockIOPool.setFailover(true);                          //当一个memcached服务器失效的时候是否去连接另一个memcached服务器.  
  30.          sockIOPool.setInitConn(10);                            //初始化时对每个服务器建立的连接数目  
  31.          sockIOPool.setMinConn(10);                             //每个服务器建立最小的连接数  
  32.          sockIOPool.setMaxConn(100);                            //每个服务器建立最大的连接数  
  33.          sockIOPool.setMaintSleep(30);                          //自查线程周期进行工作,其每次休眠时间  
  34.          sockIOPool.setNagle(false);                            //Socket的参数,如果是true在写数据时不缓冲,立即发送出去。Tcp的规则是在发送一个包之前,包的发送方会等待远程接收方确认已收到上一次发送过来的包;这个方法就可以关闭套接字的缓存——包准备立即发出。  
  35.          sockIOPool.setSocketTO(3000);                          //Socket阻塞读取数据的超时时间  
  36.          sockIOPool.setAliveCheck(true);                        //设置是否检查memcached服务器是否失效  
  37.          sockIOPool.setMaxIdle(1000*30*30);                     // 设置最大处理时间   
  38.          sockIOPool.setSocketConnectTO(0);                      //连接建立时对超时的控制  
  39.   
  40.          sockIOPool.initialize();                               // 初始化连接池  
  41.          if (memCachedClient == null){  
  42.              memCachedClient = new MemCachedClient();  
  43.              memCachedClient.setPrimitiveAsString(true);        //是否将基本类型转换为String类型  
  44.          }  
  45.     }  
  46.   
  47.     private MemcachedUtils() {  
  48.     }  
  49.   
  50.     /** 
  51.      * 向缓存添加键值对。注意:如果键已经存在,则之前的键对应的值将被替换。 
  52.      *  
  53.      * @author GaoHuanjie 
  54.      */  
  55.     public static boolean set(String key, Object value) {  
  56.         try {  
  57.             return memCachedClient.set(key, value);  
  58.         } catch (Exception e) {  
  59.             MemcachedLogUtils.writeLog(”Memcached set方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  60.             return false;  
  61.         }  
  62.     }  
  63.   
  64.     /** 
  65.      * 向缓存添加键值对并为该键值对设定逾期时间(即多长时间后该键值对从Memcached内存缓存中删除,比如: new Date(1000*10),则表示十秒之后从Memcached内存缓存中删除)。注意:如果键已经存在,则之前的键对应的值将被替换。 
  66.      *  
  67.      * @author GaoHuanjie 
  68.      */  
  69.     public static boolean set(String key, Object value, Date expire) {  
  70.         try {  
  71.             return memCachedClient.set(key, value, expire);  
  72.         } catch (Exception e) {  
  73.             MemcachedLogUtils.writeLog(”Memcached set方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  74.             return false;  
  75.         }  
  76.     }  
  77.   
  78.     /** 
  79.      * 向缓存添加键值对。注意:仅当缓存中不存在键时,才会添加成功。 
  80.      *  
  81.      * @author GaoHuanjie 
  82.      */  
  83.     public static boolean add(String key, Object value) {  
  84.         try {  
  85.             if (get(key) != null) {  
  86.                 MemcachedLogUtils.writeLog(”Memcached add方法报错,key值:” + key + “\r\n” + exceptionWrite(new Exception(“Memcached内存缓存中已经存在该键值对”)));  
  87.                 return false;  
  88.             }else{  
  89.                 return memCachedClient.add(key, value);  
  90.             }  
  91.         } catch (Exception e) {  
  92.             MemcachedLogUtils.writeLog(”Memcached add方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  93.             return false;  
  94.         }  
  95.     }  
  96.   
  97.     /** 
  98.      * 向缓存添加键值对并为该键值对设定逾期时间(即多长时间后该键值对从Memcached内存缓存中删除,比如: new Date(1000*10),则表示十秒之后从Memcached内存缓存中删除)。注意:仅当缓存中不存在键时,才会添加成功。 
  99.      *  
  100.      * @author GaoHuanjie 
  101.      */  
  102.     public static boolean add(String key, Object value, Date expire) {  
  103.         try {  
  104.             if (get(key) != null) {  
  105.                 MemcachedLogUtils.writeLog(”Memcached add方法报错,key值:” + key + “\r\n” + exceptionWrite(new Exception(“Memcached内存缓存中已经存在该键值对”)));  
  106.                 return false;  
  107.             }else{  
  108.                 return memCachedClient.add(key, value, expire);  
  109.             }  
  110.         } catch (Exception e) {  
  111.             MemcachedLogUtils.writeLog(”Memcached add方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  112.             return false;  
  113.         }  
  114.     }  
  115.   
  116.     /** 
  117.      * 根据键来替换Memcached内存缓存中已有的对应的值。注意:只有该键存在时,才会替换键相应的值。 
  118.      *  
  119.      * @author GaoHuanjie 
  120.      */  
  121.     public static boolean replace(String key, Object newValue) {  
  122.         try {  
  123.             return memCachedClient.replace(key, newValue);  
  124.         } catch (Exception e) {  
  125.             MemcachedLogUtils.writeLog(”Memcached replace方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  126.             return false;  
  127.         }  
  128.     }  
  129.   
  130.     /** 
  131.      * 根据键来替换Memcached内存缓存中已有的对应的值并设置逾期时间(即多长时间后该键值对从Memcached内存缓存中删除,比如: new Date(1000*10),则表示十秒之后从Memcached内存缓存中删除)。注意:只有该键存在时,才会替换键相应的值。 
  132.      *  
  133.      * @author GaoHuanjie 
  134.      */  
  135.     public static boolean replace(String key, Object newValue, Date expireDate) {  
  136.         try {  
  137.             return memCachedClient.replace(key, newValue, expireDate);  
  138.         } catch (Exception e) {  
  139.             MemcachedLogUtils.writeLog(”Memcached replace方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  140.             return false;  
  141.         }  
  142.     }  
  143.   
  144.     /** 
  145.      * 根据键获取Memcached内存缓存管理系统中相应的值 
  146.      *  
  147.      * @author GaoHuanjie 
  148.      */  
  149.     public static Object get(String key) {  
  150.         try {  
  151.             return memCachedClient.get(key);  
  152.         } catch (Exception e) {  
  153.             MemcachedLogUtils.writeLog(”Memcached get方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  154.             return null;  
  155.         }  
  156.     }  
  157.   
  158.     /** 
  159.      * 根据键删除memcached中的键/值对 
  160.      *  
  161.      * @author GaoHuanjie 
  162.      */  
  163.     public static boolean delete(String key) {  
  164.         try {  
  165.             return memCachedClient.delete(key);  
  166.         } catch (Exception e) {  
  167.             MemcachedLogUtils.writeLog(”Memcached delete方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  168.             return false;  
  169.         }  
  170.     }  
  171.   
  172.     /** 
  173.      * 根据键和逾期时间(例如:new Date(1000*10):十秒后过期)删除 memcached中的键/值对 
  174.      *  
  175.      * @author GaoHuanjie 
  176.      */  
  177.     public static boolean delete(String key, Date expireDate) {  
  178.         try {  
  179.             return memCachedClient.delete(key, expireDate);  
  180.         } catch (Exception e) {  
  181.             MemcachedLogUtils.writeLog(”Memcached delete方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  182.             return false;  
  183.         }  
  184.     }  
  185.   
  186.     /** 
  187.      * 清理缓存中的所有键/值对 
  188.      *  
  189.      * @author GaoHuanjie 
  190.      */  
  191.     public static boolean flashAll() {  
  192.         try {  
  193.             return memCachedClient.flushAll();  
  194.         } catch (Exception e) {  
  195.             MemcachedLogUtils.writeLog(”Memcached flashAll方法报错\r\n” + exceptionWrite(e));  
  196.             return false;  
  197.         }  
  198.     }  
  199.   
  200.     /** 
  201.      * 返回String类型的异常栈信息 
  202.      *  
  203.      * @author GaoHuanjie 
  204.      */  
  205.     private static String exceptionWrite(Exception exception) {  
  206.         StringWriter stringWriter = new StringWriter();  
  207.         PrintWriter printWriter = new PrintWriter(stringWriter);  
  208.         exception.printStackTrace(printWriter);  
  209.         printWriter.flush();  
  210.         return stringWriter.toString();  
  211.     }  
  212.   
  213.     /** 
  214.      * Memcached日志记录工具 
  215.      *  
  216.      * @author GaoHuanjie 
  217.      */  
  218.     private static class MemcachedLogUtils {  
  219.   
  220.         private static FileWriter fileWriter;  
  221.         private static BufferedWriter logWrite;  
  222.         private final static String PID = ManagementFactory.getRuntimeMXBean().getName();// 通过找到对应的JVM进程获取PID  
  223.   
  224.         /** 
  225.          * 初始化Memcached日志写入流 
  226.          *  
  227.          * @author GaoHuanjie 
  228.          */  
  229.         static {  
  230.             try {  
  231.                 String osName = System.getProperty(”os.name”);  
  232.                 if (osName.contains(“Windows”)) {  
  233.                     fileWriter = new FileWriter(“D:\\memcached.log”true);  
  234.                 } else {  
  235.                     fileWriter = new FileWriter(“/usr/local/logs/memcached.log”true);  
  236.                 }  
  237.                 logWrite = new BufferedWriter(fileWriter);  
  238.             } catch (IOException iOException) {  
  239.                 iOException.printStackTrace();  
  240.                 try {  
  241.                     if (fileWriter != null) {  
  242.                         fileWriter.close();  
  243.                     }  
  244.                     if (logWrite != null) {  
  245.                         logWrite.close();  
  246.                     }  
  247.                 } catch (Exception exception) {  
  248.                     exception.printStackTrace();  
  249.                 }  
  250.             }  
  251.         }  
  252.           
  253.         /** 
  254.          * 写入日志信息 
  255.          *  
  256.          * @author GaoHuanjie 
  257.          */  
  258.         public static void writeLog(String logContent) {  
  259.             try {  
  260.                 logWrite.write(”[“ + PID + “] ” + “- [“ + new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”).format(new Date()) + “]\r\n” + logContent);  
  261.                 logWrite.newLine();  
  262.                 logWrite.flush();  
  263.             } catch (IOException e) {  
  264.                 e.printStackTrace();  
  265.             }  
  266.         }  
  267.     }  
  268. }  
package com.ghj.packageoftool;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

/**
 * Memcached工具类
 * 
 * @author GaoHuanjie
 */
public class MemcachedUtils {

    private static MemCachedClient memCachedClient;
    static {
         /************************************配置Memcached**************************************/
         SockIOPool sockIOPool = SockIOPool.getInstance();

         sockIOPool.setServers(new String[]{"127.0.0.1:11211"});//设置memcached服务器地址
         sockIOPool.setWeights(new Integer[]{3});               //设置每个MemCached服务器权重 
         sockIOPool.setFailover(true);                          //当一个memcached服务器失效的时候是否去连接另一个memcached服务器.
         sockIOPool.setInitConn(10);                            //初始化时对每个服务器建立的连接数目
         sockIOPool.setMinConn(10);                             //每个服务器建立最小的连接数
         sockIOPool.setMaxConn(100);                            //每个服务器建立最大的连接数
         sockIOPool.setMaintSleep(30);                          //自查线程周期进行工作,其每次休眠时间
         sockIOPool.setNagle(false);                            //Socket的参数,如果是true在写数据时不缓冲,立即发送出去。Tcp的规则是在发送一个包之前,包的发送方会等待远程接收方确认已收到上一次发送过来的包;这个方法就可以关闭套接字的缓存——包准备立即发出。
         sockIOPool.setSocketTO(3000);                          //Socket阻塞读取数据的超时时间
         sockIOPool.setAliveCheck(true);                        //设置是否检查memcached服务器是否失效
         sockIOPool.setMaxIdle(1000*30*30);                     // 设置最大处理时间 
         sockIOPool.setSocketConnectTO(0);                      //连接建立时对超时的控制

         sockIOPool.initialize();                               // 初始化连接池
         if (memCachedClient == null){
             memCachedClient = new MemCachedClient();
             memCachedClient.setPrimitiveAsString(true);        //是否将基本类型转换为String类型
         }
    }

    private MemcachedUtils() {
    }

    /**
     * 向缓存添加键值对。注意:如果键已经存在,则之前的键对应的值将被替换。
     * 
     * @author GaoHuanjie
     */
    public static boolean set(String key, Object value) {
        try {
            return memCachedClient.set(key, value);
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached set方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 向缓存添加键值对并为该键值对设定逾期时间(即多长时间后该键值对从Memcached内存缓存中删除,比如: new Date(1000*10),则表示十秒之后从Memcached内存缓存中删除)。注意:如果键已经存在,则之前的键对应的值将被替换。
     * 
     * @author GaoHuanjie
     */
    public static boolean set(String key, Object value, Date expire) {
        try {
            return memCachedClient.set(key, value, expire);
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached set方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 向缓存添加键值对。注意:仅当缓存中不存在键时,才会添加成功。
     * 
     * @author GaoHuanjie
     */
    public static boolean add(String key, Object value) {
        try {
            if (get(key) != null) {
                MemcachedLogUtils.writeLog("Memcached add方法报错,key值:" + key + "\r\n" + exceptionWrite(new Exception("Memcached内存缓存中已经存在该键值对")));
                return false;
            }else{
                return memCachedClient.add(key, value);
            }
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached add方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 向缓存添加键值对并为该键值对设定逾期时间(即多长时间后该键值对从Memcached内存缓存中删除,比如: new Date(1000*10),则表示十秒之后从Memcached内存缓存中删除)。注意:仅当缓存中不存在键时,才会添加成功。
     * 
     * @author GaoHuanjie
     */
    public static boolean add(String key, Object value, Date expire) {
        try {
            if (get(key) != null) {
                MemcachedLogUtils.writeLog("Memcached add方法报错,key值:" + key + "\r\n" + exceptionWrite(new Exception("Memcached内存缓存中已经存在该键值对")));
                return false;
            }else{
                return memCachedClient.add(key, value, expire);
            }
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached add方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 根据键来替换Memcached内存缓存中已有的对应的值。注意:只有该键存在时,才会替换键相应的值。
     * 
     * @author GaoHuanjie
     */
    public static boolean replace(String key, Object newValue) {
        try {
            return memCachedClient.replace(key, newValue);
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached replace方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 根据键来替换Memcached内存缓存中已有的对应的值并设置逾期时间(即多长时间后该键值对从Memcached内存缓存中删除,比如: new Date(1000*10),则表示十秒之后从Memcached内存缓存中删除)。注意:只有该键存在时,才会替换键相应的值。
     * 
     * @author GaoHuanjie
     */
    public static boolean replace(String key, Object newValue, Date expireDate) {
        try {
            return memCachedClient.replace(key, newValue, expireDate);
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached replace方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 根据键获取Memcached内存缓存管理系统中相应的值
     * 
     * @author GaoHuanjie
     */
    public static Object get(String key) {
        try {
            return memCachedClient.get(key);
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached get方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return null;
        }
    }

    /**
     * 根据键删除memcached中的键/值对
     * 
     * @author GaoHuanjie
     */
    public static boolean delete(String key) {
        try {
            return memCachedClient.delete(key);
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached delete方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 根据键和逾期时间(例如:new Date(1000*10):十秒后过期)删除 memcached中的键/值对
     * 
     * @author GaoHuanjie
     */
    public static boolean delete(String key, Date expireDate) {
        try {
            return memCachedClient.delete(key, expireDate);
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached delete方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 清理缓存中的所有键/值对
     * 
     * @author GaoHuanjie
     */
    public static boolean flashAll() {
        try {
            return memCachedClient.flushAll();
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached flashAll方法报错\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 返回String类型的异常栈信息
     * 
     * @author GaoHuanjie
     */
    private static String exceptionWrite(Exception exception) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        exception.printStackTrace(printWriter);
        printWriter.flush();
        return stringWriter.toString();
    }

    /**
     * Memcached日志记录工具
     * 
     * @author GaoHuanjie
     */
    private static class MemcachedLogUtils {

        private static FileWriter fileWriter;
        private static BufferedWriter logWrite;
        private final static String PID = ManagementFactory.getRuntimeMXBean().getName();// 通过找到对应的JVM进程获取PID

        /**
         * 初始化Memcached日志写入流
         * 
         * @author GaoHuanjie
         */
        static {
            try {
                String osName = System.getProperty("os.name");
                if (osName.contains("Windows")) {
                    fileWriter = new FileWriter("D:\\memcached.log", true);
                } else {
                    fileWriter = new FileWriter("/usr/local/logs/memcached.log", true);
                }
                logWrite = new BufferedWriter(fileWriter);
            } catch (IOException iOException) {
                iOException.printStackTrace();
                try {
                    if (fileWriter != null) {
                        fileWriter.close();
                    }
                    if (logWrite != null) {
                        logWrite.close();
                    }
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            }
        }

        /**
         * 写入日志信息
         * 
         * @author GaoHuanjie
         */
        public static void writeLog(String logContent) {
            try {
                logWrite.write("[" + PID + "] " + "- [" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "]\r\n" + logContent);
                logWrite.newLine();
                logWrite.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

        代码二:

  1. package com.ghj.packageofclient;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import junit.framework.TestCase;  
  6.   
  7. import com.ghj.packageoftool.MemcachedUtils;  
  8.   
  9. public class Client extends TestCase{  
  10.   
  11.     /** 
  12.      * 测试MemcachedUtils类的set方法。 
  13.      *  
  14.      * @author GaoHuanjie 
  15.      */  
  16.     public static void testSet1() {  
  17.         MemcachedUtils.set(”set1Description”“调用MemcachedUtils类的set方法,没有设置键值对的存在时长”);  
  18.         System.out.println(MemcachedUtils.get(”set1Description”).toString());  
  19.     }  
  20.   
  21.     /** 
  22.      * 测试MemcachedUtils类的set方法。 
  23.      *  
  24.      * @author GaoHuanjie 
  25.      */  
  26.     public static void testSet2() {  
  27.         MemcachedUtils.set(”set2Description”“调用MemcachedUtils类的set方法,设置了键值对的存在时长——存在60秒”new Date(1000*60));  
  28.         System.out.println(MemcachedUtils.get(”set2Description”).toString());  
  29.     }  
  30.   
  31.     /** 
  32.      * 测试MemcachedUtils类的add方法。 
  33.      *  
  34.      * @author GaoHuanjie 
  35.      */  
  36.     public static void testAdd1() {  
  37.         MemcachedUtils.add(”add1Description”“调用MemcachedUtils类的add方法,没有设置键值对的存在时长”);  
  38.         System.out.println(MemcachedUtils.get(”add1Description”).toString());  
  39.     }  
  40.   
  41.     /** 
  42.      * 测试MemcachedUtils类的add方法。 
  43.      *  
  44.      * @author GaoHuanjie 
  45.      */  
  46.     public static void testAdd2() {  
  47.         MemcachedUtils.add(”add2Description”“调用MemcachedUtils类的add方法,设置了键值对的存在时长——存在60秒”new Date(1000*60));  
  48.         System.out.println(MemcachedUtils.get(”add2Description”).toString());  
  49.     }  
  50.   
  51.     /** 
  52.      * 测试MemcachedUtils类的replace方法。 
  53.      *  
  54.      * @author GaoHuanjie 
  55.      */  
  56.     public static void testReplace1() {  
  57.         MemcachedUtils.add(”replace1Description”“调用MemcachedUtils类的replace方法,没有设置键值对的存在时长”);  
  58.         MemcachedUtils.replace(”replace1Description”“值改变了!!!”);  
  59.         System.out.println(MemcachedUtils.get(”replace1Description”).toString());  
  60.     }  
  61.   
  62.     /** 
  63.      * 测试MemcachedUtils类的replace方法。 
  64.      *  
  65.      * @author GaoHuanjie 
  66.      */  
  67.     public static void testReplace2() {  
  68.         MemcachedUtils.add(”replace2Description”“调用MemcachedUtils类的replace方法,设置了键值对的存在时长——存在60秒”new Date(1000*60));  
  69.         MemcachedUtils.replace(”replace2Description”“值改变了!!!”new Date(1000*60));  
  70.         System.out.println(MemcachedUtils.get(”replace2Description”).toString());  
  71.     }  
  72.   
  73.     /** 
  74.      * 测试MemcachedUtils类的get方法。 
  75.      *  
  76.      * @author GaoHuanjie 
  77.      */  
  78.     public static void testGet() {  
  79.         MemcachedUtils.add(”getDescription”“调用MemcachedUtils类的get方法,没有设置键值对的存在时长”);  
  80.         System.out.println(MemcachedUtils.get(”getDescription”).toString());  
  81.     }  
  82.   
  83.     /** 
  84.      * 测试MemcachedUtils类的delete方法。 
  85.      *  
  86.      * @author GaoHuanjie 
  87.      */  
  88.     public static void testDelete1() {  
  89.         MemcachedUtils.add(”delete1Description”“调用MemcachedUtils类的delete方法,没有设置键值对的逾期时长”);  
  90.         MemcachedUtils.delete(”delete1Description”);  
  91.         assertEquals(null, MemcachedUtils.get(“delete1Description”));  
  92.     }  
  93.   
  94.     /** 
  95.      * 测试MemcachedUtils类的delete方法。 
  96.      *  
  97.      * @author GaoHuanjie 
  98.      */  
  99.     public static void testDelete2() {  
  100.         MemcachedUtils.set(”delete2Description1”“调用MemcachedUtils类的delete方法,设置键值对的逾期时长”new Date(600*1000));  
  101.         MemcachedUtils.delete(”delete2Description1”new Date(1000*600));  
  102.         assertEquals(null, MemcachedUtils.get(“delete2Description1”));  
  103.     }  
  104.   
  105.     /** 
  106.      * 测试MemcachedUtils类的flashAll方法。 
  107.      *  
  108.      * @author GaoHuanjie 
  109.      */  
  110.     public static void testFlashAll() {  
  111.         MemcachedUtils.add(”flashAllDescription”“调用MemcachedUtils类的delete方法,没有设置键值对的预期时长”);  
  112.         MemcachedUtils.flashAll();  
  113.         assertEquals(null, MemcachedUtils.get(“flashAllDescription”));  
  114.     }  
  115. }  
package com.ghj.packageofclient;

import java.util.Date;

import junit.framework.TestCase;

import com.ghj.packageoftool.MemcachedUtils;

public class Client extends TestCase{

    /**
     * 测试MemcachedUtils类的set方法。
     * 
     * @author GaoHuanjie
     */
    public static void testSet1() {
        MemcachedUtils.set("set1Description", "调用MemcachedUtils类的set方法,没有设置键值对的存在时长");
        System.out.println(MemcachedUtils.get("set1Description").toString());
    }

    /**
     * 测试MemcachedUtils类的set方法。
     * 
     * @author GaoHuanjie
     */
    public static void testSet2() {
        MemcachedUtils.set("set2Description", "调用MemcachedUtils类的set方法,设置了键值对的存在时长——存在60秒", new Date(1000*60));
        System.out.println(MemcachedUtils.get("set2Description").toString());
    }

    /**
     * 测试MemcachedUtils类的add方法。
     * 
     * @author GaoHuanjie
     */
    public static void testAdd1() {
        MemcachedUtils.add("add1Description", "调用MemcachedUtils类的add方法,没有设置键值对的存在时长");
        System.out.println(MemcachedUtils.get("add1Description").toString());
    }

    /**
     * 测试MemcachedUtils类的add方法。
     * 
     * @author GaoHuanjie
     */
    public static void testAdd2() {
        MemcachedUtils.add("add2Description", "调用MemcachedUtils类的add方法,设置了键值对的存在时长——存在60秒", new Date(1000*60));
        System.out.println(MemcachedUtils.get("add2Description").toString());
    }

    /**
     * 测试MemcachedUtils类的replace方法。
     * 
     * @author GaoHuanjie
     */
    public static void testReplace1() {
        MemcachedUtils.add("replace1Description", "调用MemcachedUtils类的replace方法,没有设置键值对的存在时长");
        MemcachedUtils.replace("replace1Description", "值改变了!!!");
        System.out.println(MemcachedUtils.get("replace1Description").toString());
    }

    /**
     * 测试MemcachedUtils类的replace方法。
     * 
     * @author GaoHuanjie
     */
    public static void testReplace2() {
        MemcachedUtils.add("replace2Description", "调用MemcachedUtils类的replace方法,设置了键值对的存在时长——存在60秒", new Date(1000*60));
        MemcachedUtils.replace("replace2Description", "值改变了!!!", new Date(1000*60));
        System.out.println(MemcachedUtils.get("replace2Description").toString());
    }

    /**
     * 测试MemcachedUtils类的get方法。
     * 
     * @author GaoHuanjie
     */
    public static void testGet() {
        MemcachedUtils.add("getDescription", "调用MemcachedUtils类的get方法,没有设置键值对的存在时长");
        System.out.println(MemcachedUtils.get("getDescription").toString());
    }

    /**
     * 测试MemcachedUtils类的delete方法。
     * 
     * @author GaoHuanjie
     */
    public static void testDelete1() {
        MemcachedUtils.add("delete1Description", "调用MemcachedUtils类的delete方法,没有设置键值对的逾期时长");
        MemcachedUtils.delete("delete1Description");
        assertEquals(null, MemcachedUtils.get("delete1Description"));
    }

    /**
     * 测试MemcachedUtils类的delete方法。
     * 
     * @author GaoHuanjie
     */
    public static void testDelete2() {
        MemcachedUtils.set("delete2Description1", "调用MemcachedUtils类的delete方法,设置键值对的逾期时长", new Date(600*1000));
        MemcachedUtils.delete("delete2Description1", new Date(1000*600));
        assertEquals(null, MemcachedUtils.get("delete2Description1"));
    }

    /**
     * 测试MemcachedUtils类的flashAll方法。
     * 
     * @author GaoHuanjie
     */
    public static void testFlashAll() {
        MemcachedUtils.add("flashAllDescription", "调用MemcachedUtils类的delete方法,没有设置键值对的预期时长");
        MemcachedUtils.flashAll();
        assertEquals(null, MemcachedUtils.get("flashAllDescription"));
    }
}
        总结:

        1、上面是一个完整的例子,由于该Memcached例子需要依赖特定的jar包,所以直接拷贝并不能运行,【0分下载完整Demo

        2、尽管使用Java编程语言实现了对Memcached的操作,但是其中delete(String key, Date expireDate)似乎在Windows操作系统中不怎么好用——可以按照key删除Memcached缓存中的数据,但是后面的逾期时间参数始终不起作用难过,望知道者指点一二。

转自:http://blog.csdn.net/gaohuanjie/article/details/41913017

        总结一下如何使用Java操作Memcached:

        代码一:

  1. package com.ghj.packageoftool;  
  2.   
  3. import java.io.BufferedWriter;  
  4. import java.io.FileWriter;  
  5. import java.io.IOException;  
  6. import java.io.PrintWriter;  
  7. import java.io.StringWriter;  
  8. import java.lang.management.ManagementFactory;  
  9. import java.text.SimpleDateFormat;  
  10. import java.util.Date;  
  11.   
  12. import com.danga.MemCached.MemCachedClient;  
  13. import com.danga.MemCached.SockIOPool;  
  14.   
  15. /** 
  16.  * Memcached工具类 
  17.  *  
  18.  * @author GaoHuanjie 
  19.  */  
  20. public class MemcachedUtils {  
  21.   
  22.     private static MemCachedClient memCachedClient;  
  23.     static {  
  24.          /************************************配置Memcached**************************************/  
  25.          SockIOPool sockIOPool = SockIOPool.getInstance();  
  26.   
  27.          sockIOPool.setServers(new String[]{“127.0.0.1:11211”});//设置memcached服务器地址  
  28.          sockIOPool.setWeights(new Integer[]{3});               //设置每个MemCached服务器权重   
  29.          sockIOPool.setFailover(true);                          //当一个memcached服务器失效的时候是否去连接另一个memcached服务器.  
  30.          sockIOPool.setInitConn(10);                            //初始化时对每个服务器建立的连接数目  
  31.          sockIOPool.setMinConn(10);                             //每个服务器建立最小的连接数  
  32.          sockIOPool.setMaxConn(100);                            //每个服务器建立最大的连接数  
  33.          sockIOPool.setMaintSleep(30);                          //自查线程周期进行工作,其每次休眠时间  
  34.          sockIOPool.setNagle(false);                            //Socket的参数,如果是true在写数据时不缓冲,立即发送出去。Tcp的规则是在发送一个包之前,包的发送方会等待远程接收方确认已收到上一次发送过来的包;这个方法就可以关闭套接字的缓存——包准备立即发出。  
  35.          sockIOPool.setSocketTO(3000);                          //Socket阻塞读取数据的超时时间  
  36.          sockIOPool.setAliveCheck(true);                        //设置是否检查memcached服务器是否失效  
  37.          sockIOPool.setMaxIdle(1000*30*30);                     // 设置最大处理时间   
  38.          sockIOPool.setSocketConnectTO(0);                      //连接建立时对超时的控制  
  39.   
  40.          sockIOPool.initialize();                               // 初始化连接池  
  41.          if (memCachedClient == null){  
  42.              memCachedClient = new MemCachedClient();  
  43.              memCachedClient.setPrimitiveAsString(true);        //是否将基本类型转换为String类型  
  44.          }  
  45.     }  
  46.   
  47.     private MemcachedUtils() {  
  48.     }  
  49.   
  50.     /** 
  51.      * 向缓存添加键值对。注意:如果键已经存在,则之前的键对应的值将被替换。 
  52.      *  
  53.      * @author GaoHuanjie 
  54.      */  
  55.     public static boolean set(String key, Object value) {  
  56.         try {  
  57.             return memCachedClient.set(key, value);  
  58.         } catch (Exception e) {  
  59.             MemcachedLogUtils.writeLog(”Memcached set方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  60.             return false;  
  61.         }  
  62.     }  
  63.   
  64.     /** 
  65.      * 向缓存添加键值对并为该键值对设定逾期时间(即多长时间后该键值对从Memcached内存缓存中删除,比如: new Date(1000*10),则表示十秒之后从Memcached内存缓存中删除)。注意:如果键已经存在,则之前的键对应的值将被替换。 
  66.      *  
  67.      * @author GaoHuanjie 
  68.      */  
  69.     public static boolean set(String key, Object value, Date expire) {  
  70.         try {  
  71.             return memCachedClient.set(key, value, expire);  
  72.         } catch (Exception e) {  
  73.             MemcachedLogUtils.writeLog(”Memcached set方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  74.             return false;  
  75.         }  
  76.     }  
  77.   
  78.     /** 
  79.      * 向缓存添加键值对。注意:仅当缓存中不存在键时,才会添加成功。 
  80.      *  
  81.      * @author GaoHuanjie 
  82.      */  
  83.     public static boolean add(String key, Object value) {  
  84.         try {  
  85.             if (get(key) != null) {  
  86.                 MemcachedLogUtils.writeLog(”Memcached add方法报错,key值:” + key + “\r\n” + exceptionWrite(new Exception(“Memcached内存缓存中已经存在该键值对”)));  
  87.                 return false;  
  88.             }else{  
  89.                 return memCachedClient.add(key, value);  
  90.             }  
  91.         } catch (Exception e) {  
  92.             MemcachedLogUtils.writeLog(”Memcached add方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  93.             return false;  
  94.         }  
  95.     }  
  96.   
  97.     /** 
  98.      * 向缓存添加键值对并为该键值对设定逾期时间(即多长时间后该键值对从Memcached内存缓存中删除,比如: new Date(1000*10),则表示十秒之后从Memcached内存缓存中删除)。注意:仅当缓存中不存在键时,才会添加成功。 
  99.      *  
  100.      * @author GaoHuanjie 
  101.      */  
  102.     public static boolean add(String key, Object value, Date expire) {  
  103.         try {  
  104.             if (get(key) != null) {  
  105.                 MemcachedLogUtils.writeLog(”Memcached add方法报错,key值:” + key + “\r\n” + exceptionWrite(new Exception(“Memcached内存缓存中已经存在该键值对”)));  
  106.                 return false;  
  107.             }else{  
  108.                 return memCachedClient.add(key, value, expire);  
  109.             }  
  110.         } catch (Exception e) {  
  111.             MemcachedLogUtils.writeLog(”Memcached add方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  112.             return false;  
  113.         }  
  114.     }  
  115.   
  116.     /** 
  117.      * 根据键来替换Memcached内存缓存中已有的对应的值。注意:只有该键存在时,才会替换键相应的值。 
  118.      *  
  119.      * @author GaoHuanjie 
  120.      */  
  121.     public static boolean replace(String key, Object newValue) {  
  122.         try {  
  123.             return memCachedClient.replace(key, newValue);  
  124.         } catch (Exception e) {  
  125.             MemcachedLogUtils.writeLog(”Memcached replace方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  126.             return false;  
  127.         }  
  128.     }  
  129.   
  130.     /** 
  131.      * 根据键来替换Memcached内存缓存中已有的对应的值并设置逾期时间(即多长时间后该键值对从Memcached内存缓存中删除,比如: new Date(1000*10),则表示十秒之后从Memcached内存缓存中删除)。注意:只有该键存在时,才会替换键相应的值。 
  132.      *  
  133.      * @author GaoHuanjie 
  134.      */  
  135.     public static boolean replace(String key, Object newValue, Date expireDate) {  
  136.         try {  
  137.             return memCachedClient.replace(key, newValue, expireDate);  
  138.         } catch (Exception e) {  
  139.             MemcachedLogUtils.writeLog(”Memcached replace方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  140.             return false;  
  141.         }  
  142.     }  
  143.   
  144.     /** 
  145.      * 根据键获取Memcached内存缓存管理系统中相应的值 
  146.      *  
  147.      * @author GaoHuanjie 
  148.      */  
  149.     public static Object get(String key) {  
  150.         try {  
  151.             return memCachedClient.get(key);  
  152.         } catch (Exception e) {  
  153.             MemcachedLogUtils.writeLog(”Memcached get方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  154.             return null;  
  155.         }  
  156.     }  
  157.   
  158.     /** 
  159.      * 根据键删除memcached中的键/值对 
  160.      *  
  161.      * @author GaoHuanjie 
  162.      */  
  163.     public static boolean delete(String key) {  
  164.         try {  
  165.             return memCachedClient.delete(key);  
  166.         } catch (Exception e) {  
  167.             MemcachedLogUtils.writeLog(”Memcached delete方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  168.             return false;  
  169.         }  
  170.     }  
  171.   
  172.     /** 
  173.      * 根据键和逾期时间(例如:new Date(1000*10):十秒后过期)删除 memcached中的键/值对 
  174.      *  
  175.      * @author GaoHuanjie 
  176.      */  
  177.     public static boolean delete(String key, Date expireDate) {  
  178.         try {  
  179.             return memCachedClient.delete(key, expireDate);  
  180.         } catch (Exception e) {  
  181.             MemcachedLogUtils.writeLog(”Memcached delete方法报错,key值:” + key + “\r\n” + exceptionWrite(e));  
  182.             return false;  
  183.         }  
  184.     }  
  185.   
  186.     /** 
  187.      * 清理缓存中的所有键/值对 
  188.      *  
  189.      * @author GaoHuanjie 
  190.      */  
  191.     public static boolean flashAll() {  
  192.         try {  
  193.             return memCachedClient.flushAll();  
  194.         } catch (Exception e) {  
  195.             MemcachedLogUtils.writeLog(”Memcached flashAll方法报错\r\n” + exceptionWrite(e));  
  196.             return false;  
  197.         }  
  198.     }  
  199.   
  200.     /** 
  201.      * 返回String类型的异常栈信息 
  202.      *  
  203.      * @author GaoHuanjie 
  204.      */  
  205.     private static String exceptionWrite(Exception exception) {  
  206.         StringWriter stringWriter = new StringWriter();  
  207.         PrintWriter printWriter = new PrintWriter(stringWriter);  
  208.         exception.printStackTrace(printWriter);  
  209.         printWriter.flush();  
  210.         return stringWriter.toString();  
  211.     }  
  212.   
  213.     /** 
  214.      * Memcached日志记录工具 
  215.      *  
  216.      * @author GaoHuanjie 
  217.      */  
  218.     private static class MemcachedLogUtils {  
  219.   
  220.         private static FileWriter fileWriter;  
  221.         private static BufferedWriter logWrite;  
  222.         private final static String PID = ManagementFactory.getRuntimeMXBean().getName();// 通过找到对应的JVM进程获取PID  
  223.   
  224.         /** 
  225.          * 初始化Memcached日志写入流 
  226.          *  
  227.          * @author GaoHuanjie 
  228.          */  
  229.         static {  
  230.             try {  
  231.                 String osName = System.getProperty(”os.name”);  
  232.                 if (osName.contains(“Windows”)) {  
  233.                     fileWriter = new FileWriter(“D:\\memcached.log”true);  
  234.                 } else {  
  235.                     fileWriter = new FileWriter(“/usr/local/logs/memcached.log”true);  
  236.                 }  
  237.                 logWrite = new BufferedWriter(fileWriter);  
  238.             } catch (IOException iOException) {  
  239.                 iOException.printStackTrace();  
  240.                 try {  
  241.                     if (fileWriter != null) {  
  242.                         fileWriter.close();  
  243.                     }  
  244.                     if (logWrite != null) {  
  245.                         logWrite.close();  
  246.                     }  
  247.                 } catch (Exception exception) {  
  248.                     exception.printStackTrace();  
  249.                 }  
  250.             }  
  251.         }  
  252.           
  253.         /** 
  254.          * 写入日志信息 
  255.          *  
  256.          * @author GaoHuanjie 
  257.          */  
  258.         public static void writeLog(String logContent) {  
  259.             try {  
  260.                 logWrite.write(”[“ + PID + “] ” + “- [“ + new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”).format(new Date()) + “]\r\n” + logContent);  
  261.                 logWrite.newLine();  
  262.                 logWrite.flush();  
  263.             } catch (IOException e) {  
  264.                 e.printStackTrace();  
  265.             }  
  266.         }  
  267.     }  
  268. }  
package com.ghj.packageoftool;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

/**
 * Memcached工具类
 * 
 * @author GaoHuanjie
 */
public class MemcachedUtils {

    private static MemCachedClient memCachedClient;
    static {
         /************************************配置Memcached**************************************/
         SockIOPool sockIOPool = SockIOPool.getInstance();

         sockIOPool.setServers(new String[]{"127.0.0.1:11211"});//设置memcached服务器地址
         sockIOPool.setWeights(new Integer[]{3});               //设置每个MemCached服务器权重 
         sockIOPool.setFailover(true);                          //当一个memcached服务器失效的时候是否去连接另一个memcached服务器.
         sockIOPool.setInitConn(10);                            //初始化时对每个服务器建立的连接数目
         sockIOPool.setMinConn(10);                             //每个服务器建立最小的连接数
         sockIOPool.setMaxConn(100);                            //每个服务器建立最大的连接数
         sockIOPool.setMaintSleep(30);                          //自查线程周期进行工作,其每次休眠时间
         sockIOPool.setNagle(false);                            //Socket的参数,如果是true在写数据时不缓冲,立即发送出去。Tcp的规则是在发送一个包之前,包的发送方会等待远程接收方确认已收到上一次发送过来的包;这个方法就可以关闭套接字的缓存——包准备立即发出。
         sockIOPool.setSocketTO(3000);                          //Socket阻塞读取数据的超时时间
         sockIOPool.setAliveCheck(true);                        //设置是否检查memcached服务器是否失效
         sockIOPool.setMaxIdle(1000*30*30);                     // 设置最大处理时间 
         sockIOPool.setSocketConnectTO(0);                      //连接建立时对超时的控制

         sockIOPool.initialize();                               // 初始化连接池
         if (memCachedClient == null){
             memCachedClient = new MemCachedClient();
             memCachedClient.setPrimitiveAsString(true);        //是否将基本类型转换为String类型
         }
    }

    private MemcachedUtils() {
    }

    /**
     * 向缓存添加键值对。注意:如果键已经存在,则之前的键对应的值将被替换。
     * 
     * @author GaoHuanjie
     */
    public static boolean set(String key, Object value) {
        try {
            return memCachedClient.set(key, value);
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached set方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 向缓存添加键值对并为该键值对设定逾期时间(即多长时间后该键值对从Memcached内存缓存中删除,比如: new Date(1000*10),则表示十秒之后从Memcached内存缓存中删除)。注意:如果键已经存在,则之前的键对应的值将被替换。
     * 
     * @author GaoHuanjie
     */
    public static boolean set(String key, Object value, Date expire) {
        try {
            return memCachedClient.set(key, value, expire);
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached set方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 向缓存添加键值对。注意:仅当缓存中不存在键时,才会添加成功。
     * 
     * @author GaoHuanjie
     */
    public static boolean add(String key, Object value) {
        try {
            if (get(key) != null) {
                MemcachedLogUtils.writeLog("Memcached add方法报错,key值:" + key + "\r\n" + exceptionWrite(new Exception("Memcached内存缓存中已经存在该键值对")));
                return false;
            }else{
                return memCachedClient.add(key, value);
            }
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached add方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 向缓存添加键值对并为该键值对设定逾期时间(即多长时间后该键值对从Memcached内存缓存中删除,比如: new Date(1000*10),则表示十秒之后从Memcached内存缓存中删除)。注意:仅当缓存中不存在键时,才会添加成功。
     * 
     * @author GaoHuanjie
     */
    public static boolean add(String key, Object value, Date expire) {
        try {
            if (get(key) != null) {
                MemcachedLogUtils.writeLog("Memcached add方法报错,key值:" + key + "\r\n" + exceptionWrite(new Exception("Memcached内存缓存中已经存在该键值对")));
                return false;
            }else{
                return memCachedClient.add(key, value, expire);
            }
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached add方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 根据键来替换Memcached内存缓存中已有的对应的值。注意:只有该键存在时,才会替换键相应的值。
     * 
     * @author GaoHuanjie
     */
    public static boolean replace(String key, Object newValue) {
        try {
            return memCachedClient.replace(key, newValue);
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached replace方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 根据键来替换Memcached内存缓存中已有的对应的值并设置逾期时间(即多长时间后该键值对从Memcached内存缓存中删除,比如: new Date(1000*10),则表示十秒之后从Memcached内存缓存中删除)。注意:只有该键存在时,才会替换键相应的值。
     * 
     * @author GaoHuanjie
     */
    public static boolean replace(String key, Object newValue, Date expireDate) {
        try {
            return memCachedClient.replace(key, newValue, expireDate);
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached replace方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 根据键获取Memcached内存缓存管理系统中相应的值
     * 
     * @author GaoHuanjie
     */
    public static Object get(String key) {
        try {
            return memCachedClient.get(key);
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached get方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return null;
        }
    }

    /**
     * 根据键删除memcached中的键/值对
     * 
     * @author GaoHuanjie
     */
    public static boolean delete(String key) {
        try {
            return memCachedClient.delete(key);
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached delete方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 根据键和逾期时间(例如:new Date(1000*10):十秒后过期)删除 memcached中的键/值对
     * 
     * @author GaoHuanjie
     */
    public static boolean delete(String key, Date expireDate) {
        try {
            return memCachedClient.delete(key, expireDate);
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached delete方法报错,key值:" + key + "\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 清理缓存中的所有键/值对
     * 
     * @author GaoHuanjie
     */
    public static boolean flashAll() {
        try {
            return memCachedClient.flushAll();
        } catch (Exception e) {
            MemcachedLogUtils.writeLog("Memcached flashAll方法报错\r\n" + exceptionWrite(e));
            return false;
        }
    }

    /**
     * 返回String类型的异常栈信息
     * 
     * @author GaoHuanjie
     */
    private static String exceptionWrite(Exception exception) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        exception.printStackTrace(printWriter);
        printWriter.flush();
        return stringWriter.toString();
    }

    /**
     * Memcached日志记录工具
     * 
     * @author GaoHuanjie
     */
    private static class MemcachedLogUtils {

        private static FileWriter fileWriter;
        private static BufferedWriter logWrite;
        private final static String PID = ManagementFactory.getRuntimeMXBean().getName();// 通过找到对应的JVM进程获取PID

        /**
         * 初始化Memcached日志写入流
         * 
         * @author GaoHuanjie
         */
        static {
            try {
                String osName = System.getProperty("os.name");
                if (osName.contains("Windows")) {
                    fileWriter = new FileWriter("D:\\memcached.log", true);
                } else {
                    fileWriter = new FileWriter("/usr/local/logs/memcached.log", true);
                }
                logWrite = new BufferedWriter(fileWriter);
            } catch (IOException iOException) {
                iOException.printStackTrace();
                try {
                    if (fileWriter != null) {
                        fileWriter.close();
                    }
                    if (logWrite != null) {
                        logWrite.close();
                    }
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            }
        }

        /**
         * 写入日志信息
         * 
         * @author GaoHuanjie
         */
        public static void writeLog(String logContent) {
            try {
                logWrite.write("[" + PID + "] " + "- [" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "]\r\n" + logContent);
                logWrite.newLine();
                logWrite.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

        代码二:

  1. package com.ghj.packageofclient;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import junit.framework.TestCase;  
  6.   
  7. import com.ghj.packageoftool.MemcachedUtils;  
  8.   
  9. public class Client extends TestCase{  
  10.   
  11.     /** 
  12.      * 测试MemcachedUtils类的set方法。 
  13.      *  
  14.      * @author GaoHuanjie 
  15.      */  
  16.     public static void testSet1() {  
  17.         MemcachedUtils.set(”set1Description”“调用MemcachedUtils类的set方法,没有设置键值对的存在时长”);  
  18.         System.out.println(MemcachedUtils.get(”set1Description”).toString());  
  19.     }  
  20.   
  21.     /** 
  22.      * 测试MemcachedUtils类的set方法。 
  23.      *  
  24.      * @author GaoHuanjie 
  25.      */  
  26.     public static void testSet2() {  
  27.         MemcachedUtils.set(”set2Description”“调用MemcachedUtils类的set方法,设置了键值对的存在时长——存在60秒”new Date(1000*60));  
  28.         System.out.println(MemcachedUtils.get(”set2Description”).toString());  
  29.     }  
  30.   
  31.     /** 
  32.      * 测试MemcachedUtils类的add方法。 
  33.      *  
  34.      * @author GaoHuanjie 
  35.      */  
  36.     public static void testAdd1() {  
  37.         MemcachedUtils.add(”add1Description”“调用MemcachedUtils类的add方法,没有设置键值对的存在时长”);  
  38.         System.out.println(MemcachedUtils.get(”add1Description”).toString());  
  39.     }  
  40.   
  41.     /** 
  42.      * 测试MemcachedUtils类的add方法。 
  43.      *  
  44.      * @author GaoHuanjie 
  45.      */  
  46.     public static void testAdd2() {  
  47.         MemcachedUtils.add(”add2Description”“调用MemcachedUtils类的add方法,设置了键值对的存在时长——存在60秒”new Date(1000*60));  
  48.         System.out.println(MemcachedUtils.get(”add2Description”).toString());  
  49.     }  
  50.   
  51.     /** 
  52.      * 测试MemcachedUtils类的replace方法。 
  53.      *  
  54.      * @author GaoHuanjie 
  55.      */  
  56.     public static void testReplace1() {  
  57.         MemcachedUtils.add(”replace1Description”“调用MemcachedUtils类的replace方法,没有设置键值对的存在时长”);  
  58.         MemcachedUtils.replace(”replace1Description”“值改变了!!!”);  
  59.         System.out.println(MemcachedUtils.get(”replace1Description”).toString());  
  60.     }  
  61.   
  62.     /** 
  63.      * 测试MemcachedUtils类的replace方法。 
  64.      *  
  65.      * @author GaoHuanjie 
  66.      */  
  67.     public static void testReplace2() {  
  68.         MemcachedUtils.add(”replace2Description”“调用MemcachedUtils类的replace方法,设置了键值对的存在时长——存在60秒”new Date(1000*60));  
  69.         MemcachedUtils.replace(”replace2Description”“值改变了!!!”new Date(1000*60));  
  70.         System.out.println(MemcachedUtils.get(”replace2Description”).toString());  
  71.     }  
  72.   
  73.     /** 
  74.      * 测试MemcachedUtils类的get方法。 
  75.      *  
  76.      * @author GaoHuanjie 
  77.      */  
  78.     public static void testGet() {  
  79.         MemcachedUtils.add(”getDescription”“调用MemcachedUtils类的get方法,没有设置键值对的存在时长”);  
  80.         System.out.println(MemcachedUtils.get(”getDescription”).toString());  
  81.     }  
  82.   
  83.     /** 
  84.      * 测试MemcachedUtils类的delete方法。 
  85.      *  
  86.      * @author GaoHuanjie 
  87.      */  
  88.     public static void testDelete1() {  
  89.         MemcachedUtils.add(”delete1Description”“调用MemcachedUtils类的delete方法,没有设置键值对的逾期时长”);  
  90.         MemcachedUtils.delete(”delete1Description”);  
  91.         assertEquals(null, MemcachedUtils.get(“delete1Description”));  
  92.     }  
  93.   
  94.     /** 
  95.      * 测试MemcachedUtils类的delete方法。 
  96.      *  
  97.      * @author GaoHuanjie 
  98.      */  
  99.     public static void testDelete2() {  
  100.         MemcachedUtils.set(”delete2Description1”“调用MemcachedUtils类的delete方法,设置键值对的逾期时长”new Date(600*1000));  
  101.         MemcachedUtils.delete(”delete2Description1”new Date(1000*600));  
  102.         assertEquals(null, MemcachedUtils.get(“delete2Description1”));  
  103.     }  
  104.   
  105.     /** 
  106.      * 测试MemcachedUtils类的flashAll方法。 
  107.      *  
  108.      * @author GaoHuanjie 
  109.      */  
  110.     public static void testFlashAll() {  
  111.         MemcachedUtils.add(”flashAllDescription”“调用MemcachedUtils类的delete方法,没有设置键值对的预期时长”);  
  112.         MemcachedUtils.flashAll();  
  113.         assertEquals(null, MemcachedUtils.get(“flashAllDescription”));  
  114.     }  
  115. }  
package com.ghj.packageofclient;

import java.util.Date;

import junit.framework.TestCase;

import com.ghj.packageoftool.MemcachedUtils;

public class Client extends TestCase{

    /**
     * 测试MemcachedUtils类的set方法。
     * 
     * @author GaoHuanjie
     */
    public static void testSet1() {
        MemcachedUtils.set("set1Description", "调用MemcachedUtils类的set方法,没有设置键值对的存在时长");
        System.out.println(MemcachedUtils.get("set1Description").toString());
    }

    /**
     * 测试MemcachedUtils类的set方法。
     * 
     * @author GaoHuanjie
     */
    public static void testSet2() {
        MemcachedUtils.set("set2Description", "调用MemcachedUtils类的set方法,设置了键值对的存在时长——存在60秒", new Date(1000*60));
        System.out.println(MemcachedUtils.get("set2Description").toString());
    }

    /**
     * 测试MemcachedUtils类的add方法。
     * 
     * @author GaoHuanjie
     */
    public static void testAdd1() {
        MemcachedUtils.add("add1Description", "调用MemcachedUtils类的add方法,没有设置键值对的存在时长");
        System.out.println(MemcachedUtils.get("add1Description").toString());
    }

    /**
     * 测试MemcachedUtils类的add方法。
     * 
     * @author GaoHuanjie
     */
    public static void testAdd2() {
        MemcachedUtils.add("add2Description", "调用MemcachedUtils类的add方法,设置了键值对的存在时长——存在60秒", new Date(1000*60));
        System.out.println(MemcachedUtils.get("add2Description").toString());
    }

    /**
     * 测试MemcachedUtils类的replace方法。
     * 
     * @author GaoHuanjie
     */
    public static void testReplace1() {
        MemcachedUtils.add("replace1Description", "调用MemcachedUtils类的replace方法,没有设置键值对的存在时长");
        MemcachedUtils.replace("replace1Description", "值改变了!!!");
        System.out.println(MemcachedUtils.get("replace1Description").toString());
    }

    /**
     * 测试MemcachedUtils类的replace方法。
     * 
     * @author GaoHuanjie
     */
    public static void testReplace2() {
        MemcachedUtils.add("replace2Description", "调用MemcachedUtils类的replace方法,设置了键值对的存在时长——存在60秒", new Date(1000*60));
        MemcachedUtils.replace("replace2Description", "值改变了!!!", new Date(1000*60));
        System.out.println(MemcachedUtils.get("replace2Description").toString());
    }

    /**
     * 测试MemcachedUtils类的get方法。
     * 
     * @author GaoHuanjie
     */
    public static void testGet() {
        MemcachedUtils.add("getDescription", "调用MemcachedUtils类的get方法,没有设置键值对的存在时长");
        System.out.println(MemcachedUtils.get("getDescription").toString());
    }

    /**
     * 测试MemcachedUtils类的delete方法。
     * 
     * @author GaoHuanjie
     */
    public static void testDelete1() {
        MemcachedUtils.add("delete1Description", "调用MemcachedUtils类的delete方法,没有设置键值对的逾期时长");
        MemcachedUtils.delete("delete1Description");
        assertEquals(null, MemcachedUtils.get("delete1Description"));
    }

    /**
     * 测试MemcachedUtils类的delete方法。
     * 
     * @author GaoHuanjie
     */
    public static void testDelete2() {
        MemcachedUtils.set("delete2Description1", "调用MemcachedUtils类的delete方法,设置键值对的逾期时长", new Date(600*1000));
        MemcachedUtils.delete("delete2Description1", new Date(1000*600));
        assertEquals(null, MemcachedUtils.get("delete2Description1"));
    }

    /**
     * 测试MemcachedUtils类的flashAll方法。
     * 
     * @author GaoHuanjie
     */
    public static void testFlashAll() {
        MemcachedUtils.add("flashAllDescription", "调用MemcachedUtils类的delete方法,没有设置键值对的预期时长");
        MemcachedUtils.flashAll();
        assertEquals(null, MemcachedUtils.get("flashAllDescription"));
    }
}
        总结:

        1、上面是一个完整的例子,由于该Memcached例子需要依赖特定的jar包,所以直接拷贝并不能运行,【0分下载完整Demo

        2、尽管使用Java编程语言实现了对Memcached的操作,但是其中delete(String key, Date expireDate)似乎在Windows操作系统中不怎么好用——可以按照key删除Memcached缓存中的数据,但是后面的逾期时间参数始终不起作用难过,望知道者指点一二。

猜你喜欢

转载自blog.csdn.net/my_csdn_lsq/article/details/79148580