日期:2014-05-16  浏览次数:20641 次

XMemcached使用示例

Memcached 是一个高性能的分布式内存对象的key-value缓存系统,用于动态Web应用以减轻数据库负载,现在也有很多人将它作为内存式数据库在使用,memcached通过它的自定义协议与客户端交互,而XMemcached就是它的一个java客户端实现。

?

XMemcached使用示例(本示例基于xmemcached-1.3.8.jar),总结一个,如下:

package com.wujintao.memcached;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.Counter;
import net.rubyeye.xmemcached.GetsResponse;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.auth.AuthInfo;
import net.rubyeye.xmemcached.command.BinaryCommandFactory;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.transcoders.StringTranscoder;
import net.rubyeye.xmemcached.utils.AddrUtil;

import org.junit.Test;

import com.wujintao.redis.util.MD5Util;

public class TestCase {
	@Test
	public void test1() throws IOException {
		MemcachedClientBuilder builder = new XMemcachedClientBuilder(
				AddrUtil.getAddresses("localhost:11211"));
		// AddrUtil.getAddresses("server1:11211 server2:11211")
		MemcachedClient client = builder.build();
		try {
			/**
			 * 第一个是存储的key名称,
			 * 第二个是expire时间(单位秒),超过这个时间,memcached将这个数据替换出去,0表示永久存储(默认是一个月)
			 * 第三个参数就是实际存储的数据
			 */
			client.set("hello", 0, "Hello,xmemcached");
			String value = client.get("hello");
			System.out.println("hello=" + value);
			client.delete("hello");
			value = client.get("hello");
			System.out.println("hello=" + value);

			// value=client.get(“hello”,3000);

			/**
			 * Memcached是通过cas协议实现原子更新,所谓原子更新就是compare and set,
			 * 原理类似乐观锁,每次请求存储某个数据同时要附带一个cas值, memcached比对这个cas值与当前存储数据的cas值是否相等,
			 * 如果相等就让新的数据覆盖老的数据,如果不相等就认为更新失败, 这在并发环境下特别有用
			 */
			GetsResponse<Integer> result = client.gets("a");
			long cas = result.getCas();
			// 尝试将a的值更新为2
			if (!client.cas("a", 0, 2, cas)) {
				System.err.println("cas error");
			}
		} catch (MemcachedException e) {
			System.err.println("MemcachedClient operation fail");
			e.printStackTrace();
		} catch (TimeoutException e) {
			System.err.println("MemcachedClient operation timeout");
			e.printStackTrace();
		} catch (InterruptedException e) {
			// ignore
		}
		try {
			// close memcached client
			client.shutdown();
		} catch (IOException e) {
			System.err.println("Shutdown MemcachedClient fail");
			e.printStackTrace();
		}

	}

	@Test
	public void test2() throws TimeoutException, InterruptedException,
			MemcachedException, IOException {
		MemcachedClientBuilder builder = new XMemcachedClientBuilder(
				AddrUtil.getAddresses("localhost:11211"));
		MemcachedClient client = builder.build();
		client.flushAll();
		if (!client.set("hello", 0, "world")) {
			System.err.println("set error");
		}
		if (client.add("hello", 0, "dennis")) {
			System.err.println("Add error,key is existed");
		}
		if (!client.replace("hello", 0, "dennis")) {
			System.err.println("replace error");
		}
		client.append("hello", " good");
		client.prepend("hello", "hello ");
		String name = client.get("hello", new StringTranscoder());
		System.out.println(name);

		/**
		 * 而删除数据则是通过deleteWithNoReply方法,这个方法删除数据并且告诉memcached
		 * 不用返回应答,因此这个方法不会等待应答直接返回,特别适合于批量处理
		 */
		client.deleteWithNoReply("hello");
	}

	@Test
	public void incrDecr() throws IOException, TimeoutException,
			InterruptedException, MemcachedException {
		MemcachedClientBuilder builder = new XMemcachedClientBuilder(
				AddrUtil.getAddresses("localhost:11211"));
		MemcachedClient client = builder.build();
		/**
		 * 第一个参数指定递增的key名称, 第二个参数指定递增的幅度大小, 第三个参数指定当key不存在的情况下的初始值。
		 * 两个参数的重载方法省略了第三个参数,默认指定为0。
		 */
		assert (1 == client.incr("a", 5, 1));
		assert (6 == client.incr("a", 5));
		assert (10 == client.incr("a", 4));
		assert (9 == client.decr("a", 1));
		assert (7 == client.decr("a", 2));
	}

	@Test
	public void counter() thro