本文复制其他播客,有好的技术文章希望各位大神能告知... 谢谢。

如何使用Java操作Memcached实例:

代码一:

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();
}
}
}
}

代码二:

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"));
}
}

Java操作Memcached的更多相关文章

  1. memcached—Java操作Memcached实例

    前面博客介绍了如何在Windows操作系统中安装Memcached,总结一下如何使用Java操作Memcached实例: 代码一: package com.ghj.packageoftool; imp ...

  2. Java操作memcached(一)

    Memcached事实上,两次Hash算法    第一次hash算法被用于定位Memcached示例    第二次hash算法是底部HashMap中间hash算法 Hash算法      1.依据余数 ...

  3. Java操作memcache

    [本文出自天外归云的博客园] 准备工作 Java操作memcache需要spymemcache类库的支持,在Eclipse中修改maven项目的pom.xml文件—— 添加仓库: <reposi ...

  4. Redis基础知识、命令以及java操作Redis

    1 nosql的概念 sql:操作(关系型)数据库的标准查询语言 关系型数据库(rdbms):以关系(由行和列组成的二维表)模型为核心数据库,有表的储存系统.(mysql.oracle.sqlserv ...

  5. Redis-基本概念、java操作redis、springboot整合redis,分布式缓存,分布式session管理等

    NoSQL的引言 Redis数据库相关指令 Redis持久化相关机制 SpringBoot操作Redis Redis分布式缓存实现 Resis中主从复制架构和哨兵机制 Redis集群搭建 Redis实 ...

  6. Java操作Sqlite数据库-jdbc连接

    Java操作Sqlite数据库步骤: 1. 导入Sqlite jdbc 本文使用sqlite-jdbc-3.7.2.jar,下载地址 http://pan.baidu.com/s/1kVHAGdD 2 ...

  7. 【MongoDB for Java】Java操作MongoDB

    上一篇文章: http://www.cnblogs.com/hoojo/archive/2011/06/01/2066426.html介绍到了在MongoDB的控制台完成MongoDB的数据操作,通过 ...

  8. Java操作Oracle

    public class DBCon { // 数据库驱动对象 public static final String DRIVER = "oracle.jdbc.driver.OracleD ...

  9. JAVA操作ORACLE数据库的存储过程

    一.任务提出 JAVA操作oracle11g存储过程实验需要完成以下几个实例: 1.调用没有返回参数的过程(插入记录.更新记录) 2.有返回参数的过程 3.返回列表的过程 4.返回带分页的列表的过程. ...

随机推荐

  1. Git添加文件改动时出错

    原来的主文件夹中替换了3个子文件夹,每个子文件夹有若干同名文件,总共替换了大概200多个文件吧. 然后在git主文件夹中使用git add .指令出现如下错误: apple@kissAir: iOS$ ...

  2. java工具类(一)之服务端java实现根据地址从百度API获取经纬度

    服务端java实现根据地址从百度API获取经纬度 代码: package com.pb.baiduapi; import java.io.BufferedReader; import java.io. ...

  3. 一个不错的扩展:Ext.ux.container.ButtonSegment

    地址:http://www.sencha.com/forum/showthread.php?132048-Ext.ux.container.ButtonSegment

  4. 中国象棋游戏Chess(2) - 走棋

    之前的文章请看:中国象棋游戏Chess(1) - 棋盘绘制以及棋子的绘制 现在实现走棋的功能. 首先需要获取点击到的棋子,用QWidget中的函数 mouseReleaseEvent 实现函数: vo ...

  5. adb shell后出现error解决方案

    解决办法: 解决办法: 1.adb kill-server 2.adb start-server 3.adb remount 4.adb shell 一般情况下都可以在此启动adb相关

  6. 运行Myeclipse时,如何删除IVM窗口

    windows------>preference------>run/debug------->lauching--------->percpectives,改成never,n ...

  7. 更改EBS服务器域名/IP

    more: 341322.1 : How to change the hostname of an Applications Tier using AutoConfig 338003.1 : How  ...

  8. DB Query Analyzer 6.02 is released, 71 articles concerned have been published

    DB Query Analyzer is presented by Master Genfeng, Ma from Chinese Mainland. It has English version n ...

  9. 图文并茂的生产者消费者应用实例demo

    前面的几篇文章<<.NET 中的阻塞队列BlockingCollection的正确打开方式>><<项目开发中应用如何并发处理的一二事>>从代码以及理论角 ...

  10. 简单的Java逻辑小代码(打擂台,冒泡排序,水仙花数,回文数,递归)

    1.打擂台 简单的小代码,打擂台.纪念下过去,祝福下新人. public static void main(String[] args){ int[] ld = {1,4,2,10,8,9,5}; i ...