实战Memcached缓存系统

1. What is Memcached?

Memcached是一个免费开源、高性能、分布式的内存对象缓存系统。Memcached是在内存中,为特定数据(字符串或对象)构建key-value的小块数据存储。

2. 下载Memcached的服务器端软件

Windows平台版本下载:http://splinedancer.com/memcached-win32/memcached-1.2.4-Win32-Preview-20080309_bin.zip

Linux平台版本下载:http://memcached.googlecode.com/files/memcached-1.4.10.tar.gz

3. 在服务器上部署Memcached Server

以下以Windows平台为例:

参考: http://www.codeforest.net/how-to-install-memcached-on-windows-machine
下载下来的Windows版本解压到C:/memcached/

在控制台输入命令安装:
 c:/memcached/memcached.exe  -d install    

启动:

 c:/memcached/memcached.exe -d  start  

或:

 net start "memcached Server"  

默认的缓存大小为64M,如果不够用,请打开注册表,找到:

 HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/memcached  Server .  

将其内容修改为:

 “C:/memcached/memcached.exe” -d runservice -m 512  

4. 下载Memcached的客户端API包

下载地址:http://spymemcached.googlecode.com/files/memcached-2.5.jar


5. 编写一个Java数据类

 
  1. package com.sinosuperman.memcached;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5.   
  6. public class User implements Serializable{   
  7.   
  8.     private static final long serialVersionUID = -372274003834027815L;  
  9.   
  10.     String userId;  
  11.       
  12.     public User(String userId) {   
  13.         super();   
  14.         this.userId = userId;   
  15.     }  
  16.       
  17.     public String getUserId() {   
  18.         return userId;   
  19.     }   
  20.       
  21.     public void setUserId(String userId) {   
  22.         this.userId = userId;   
  23.     }   
  24.           
  25.     @Override   
  26.     public String toString() {   
  27.         // TODO Auto-generated method stub    
  28.         StringBuffer sb=new StringBuffer();   
  29.         sb.append("userId="+this.userId);   
  30.         return sb.toString();   
  31.     }   
  32. }   

6. 编写一个Memcached的客户端

 
  1. package com.sinosuperman.memcached;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.InetSocketAddress;  
  5.   
  6. import net.spy.memcached.MemcachedClient;  
  7.   
  8. public class TestMemcached {  
  9.     public static void main(String[] args) throws IOException {  
  10.         MemcachedClient cache = new MemcachedClient(new InetSocketAddress("127.0.0.1"11211));  
  11.         for (int i = 1; i < 10; i++) {  
  12.             cache.set("T0001" + i, 3600new User(i + ""));   
  13.         }  
  14.         User myObject = (User) cache.get("T00011");  
  15.         System.out.println("Get object from mem :" + myObject);   
  16.     }   
  17. }  

7. 运行测试

运行结果应该如下:

 
  1. 2011-12-15 17:25:30.276 INFO net.spy.memcached.MemcachedConnection:  Added {QA sa=/127.0.0.1:11211, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue  
  2. 2011-12-15 17:25:30.292 INFO net.spy.memcached.MemcachedConnection:  Connection state changed for sun.nio.ch.SelectionKeyImpl@c62080  
  3. Get object from mem :userId=1  

1. 构造函数

 public MemcachedClient(InetSocketAddress[] ia) throws IOException;  

 public MemcachedClient(List<InetSocketAddress> addrs) throws IOException;  

 public MemcachedClient(ConnectionFactory cf, List<InetSocketAddress> addrs) throws IOException;  

其中最简单的构造函数就是第一个,可以直接传递一个InetSocketAddress,也可以是InetSocketAddress的数组。其实InetSocketAddress也是被转换成数组的。

比如:

 MemcachedClient cache = new MemcachedClient(new InetSocketAddress("127.0.0.1"11211));  

2. 常用方法

一般缓存数据的常用操作有:set(add+replace)、get、replace、add

 public Future<Boolean> set(String key, int exp, Object o)  

第一个参数:键(key)

第二个参数:过期时间(单位是秒)

第三个参数:要设置缓存中的对象(value),如果没有则插入,如果有则修改。

 public Object get(String key)  
第一个参数:键(key)

 public Future<Boolean> replace(String key, int exp, Object o)  

第一个参数:键(key)

第二个参数:过期时间(单位是秒)

第三个参数:该键的新值(new value),如果有则修改。

 public Future<Boolean> add(String key, int exp, Object o)  
第一个参数:键(key)

第二个参数:过期时间(单位是秒)

第三个参数:该键的值(value),如果没有则插入。

一、基本参数

在我们第一次安装Memcached时,一般都是用过这个命令:

 memcached -m 512 -u root -d -l 127.0.0.1 -p 11211  

我们先来解释这几个参数的含义吧。


-m 指定缓存所使用的最大内存容量,单位是Megabytes,默认是64MB

-u 只有以root身份运行时才指定该参数

-d 以daemon的形式运行

-l 指定监听的地址

-p 指定监听的TCP端口号,默认是11211


二、其他常用的参数

-t 指定线程数,默认是4个

-h 打印帮助信息

-c 最大同时连接数,默认是1024.

-U 指定监听的UDP端口号,默认是11211

-M 内存耗尽时显示错误,而不是删除项


一开始说的“-d”参数需要进行进一步的解释

-d install 安装memcached

-d uninstall 卸载memcached

-d start 启动memcached服务

-d restart 重启memcached服务

-d stop 停止memcached服务

-d shutdown 停止memcached服务


三、更多参数

使用"-h"去了解吧~


四、使用服务软件的经验

写到这里,最后说一句。在使用任何软件的时候,首先要去关注这样几点:


1. 打印帮助信息:

这个一般都是“-h”,当然也有需要“-help”才可以的。


2. 启动、停止、重启/重载配置的命令:

要注意,是同一个命令的不同参数来标识的,还是用不同的命令或脚本。


3. 配置

首先,启动是否需要配置文件。

其次,如果是比较大型的软件,一般都需要配置文件,那么默认的配置文件在哪里要清楚。

再次,指定加载配置文件的命令格式如何。


4. 指定使用内存容量、线程数、硬盘容量等

是否有这方面的配置参数需要指定,以及如何设置。


5. 日志文件

首先,是否有日志文件需要存储。

其次,如果有日志文件,默认的存储目录是什么。

最后,手动指定日志文件的命令格式如何。


6. 最大连接数

首先,是否提供监听的连接服务。

其次,如果提供,默认的最大连接数是多少。

最后,手动指定最大连接数的命令格式如何。

1. 什么是CAS协议

很多中文的资料都不会告诉大家CAS的全称是什么,不过一定不要把CAS当作中国科学院(China Academy of Sciences)的缩写。Google.com一下,CAS是什么?CAS是Check And Set的缩写。

2. CAS协议原文 http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt

3. CAS的基本原理

基本原理非常简单,一言以蔽之,就是“版本号”。每个存储的数据对象,多有一个版本号。我们可以从下面的例子来理解:

如果不采用CAS,则有如下的情景:

第一步,A取出数据对象X;

第二步,B取出数据对象X;

第三步,B修改数据对象X,并将其放入缓存;

第四步,A修改数据对象X,并将其放入缓存。

我们可以发现,第四步中会产生数据写入冲突。


如果采用CAS协议,则是如下的情景。

第一步,A取出数据对象X,并获取到CAS-ID1;

第二步,B取出数据对象X,并获取到CAS-ID2;

第三步,B修改数据对象X,在写入缓存前,检查CAS-ID与缓存空间中该数据的CAS-ID是否一致。结果是“一致”,就将修改后的带有CAS-ID2的X写入到缓存。

第四步,A修改数据对象Y,在写入缓存前,检查CAS-ID与缓存空间中该数据的CAS-ID是否一致。结果是“不一致”,则拒绝写入,返回存储失败。


这样CAS协议就用了“版本号”的思想,解决了冲突问题。

1. 非CAS

首先看一个不是CAS的Memcached程序实例。实例的问题原型,见上一篇博文。

程序实例:

 
  1. package com.sinosuperman.memcached;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.InetSocketAddress;  
  5.   
  6. import net.spy.memcached.MemcachedClient;  
  7.   
  8. public class Test {  
  9.     public static void main(String[] args) throws IOException {  
  10.         MemcachedClient cache = new MemcachedClient(new InetSocketAddress("127.0.0.1"11211));  
  11.           
  12.         cache.set("x"1800"Love");  
  13.   
  14.         String obj1 = (String) cache.get("x");  
  15.         String obj2 = (String) cache.get("x");  
  16.         obj2 = "Michael";  
  17.           
  18.         cache.set("x"1800, obj2);  
  19.         System.out.println("Non-CAS 2:t" + obj2);  
  20.         System.out.println("Non-CAS 1:t" + obj1);  
  21.     }  
  22. }  

运行结果:

 
  1. 2011-12-18 23:12:39.836 INFO net.spy.memcached.MemcachedConnection:  Added {QA sa=/127.0.0.1:11211, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue  
  2. 2011-12-18 23:12:39.843 INFO net.spy.memcached.MemcachedConnection:  Connection state changed for sun.nio.ch.SelectionKeyImpl@b09e89  
  3. Non-CAS 2:  Michael  
  4. Non-CAS 1:  Love  

可见在多个Client操作时,一定会引起写不一致性的问题。

2. CAS

程序实例:

 
  1. package com.sinosuperman.memcached;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.InetSocketAddress;  
  5.   
  6. import net.spy.memcached.CASValue;  
  7. import net.spy.memcached.MemcachedClient;  
  8.   
  9. public class Test {  
  10.     @SuppressWarnings("unchecked")  
  11.     public static void main(String[] args) throws IOException {  
  12.         MemcachedClient cache = new MemcachedClient(new InetSocketAddress("127.0.0.1"11211));  
  13.           
  14.         cache.set("y"1800"Love");  
  15.   
  16.         CASValue casValue1 = cache.gets("y");  
  17.         CASValue casValue2 = cache.gets("y");  
  18.         cache.cas("y", casValue2.getCas(), casValue2.getValue());  
  19.           
  20.         System.out.println("CAS 2:t" + casValue2.getCas());  
  21.         System.out.println("Value 2:t" + casValue2.getValue());  
  22.           
  23.         System.out.println("CAS 1:t" + casValue1.getCas());  
  24.         System.out.println("Value 1:t" + casValue1.getValue());  
  25.     }  
  26. }  

运行结果:

 
  1. 2011-12-18 23:07:14.528 INFO net.spy.memcached.MemcachedConnection:  Added {QA sa=/127.0.0.1:11211, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue  
  2. 2011-12-18 23:07:14.541 INFO net.spy.memcached.MemcachedConnection:  Connection state changed for sun.nio.ch.SelectionKeyImpl@1621e42  
  3. CAS 2:  11  
  4. Value 2:    Love  
  5. CAS 1:  11  
  6. Value 1:    Love  

1. 源程序

 
  1. package com.sinosuperman.memcached;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.InetSocketAddress;  
  5.   
  6. import net.spy.memcached.CASResponse;  
  7. import net.spy.memcached.CASValue;  
  8. import net.spy.memcached.MemcachedClient;  
  9.   
  10.   
  11. public class Test {  
  12.       
  13.     private static MemcachedClient client = null;  
  14.       
  15.     static {  
  16.         try {  
  17.             client = new MemcachedClient(new InetSocketAddress("localhost"11211));  
  18.         } catch (IOException o) {  
  19.         }  
  20.     }  
  21.   
  22.     public static void main(String[] args) throws Exception {  
  23.           
  24.         client.set("numberss"18001);  
  25.           
  26.         Test testObj = new Test();  
  27.         for (int i = 0; i < 10; i++) {  
  28.             testObj.new ThreadTest("Thread-" + (i + 1)).start();  
  29.         }  
  30.     }  
  31.       
  32.     private class ThreadTest extends Thread {  
  33.           
  34.         private  MemcachedClient client = null;  
  35.         ThreadTest(String name) throws IOException {  
  36.             super(name);  
  37.             client = new MemcachedClient(new InetSocketAddress("localhost"11211));  
  38.         }  
  39.           
  40.         public void run() {  
  41.             int i = 0;  
  42.             int success = 0;  
  43.             while (i < 10) {  
  44.                 i++;  
  45.                 CASValue<Object> uniqueValue =client.gets("numberss");  
  46.                 CASResponse response = client.cas("numberss",     
  47.                  uniqueValue.getCas(), (Integer)uniqueValue.getValue() + 1);  
  48.   
  49.                 if (response.toString().equals("OK")) {  
  50.                     success++;  
  51.                 }  
  52.                   
  53.                 if (i == 10)  
  54.                 System.out.println(Thread.currentThread().getName() + " " +  i   
  55.                   + " time " + " update oldValue : " + uniqueValue.getValue()   
  56.                   +  " , result : " + response);  
  57.             }  
  58.               
  59.             if (success < 10) {  
  60.                 Count.incr(10 - success);  
  61.                 System.out.println("Test counter: " + Count.get());  
  62.             }  
  63.         }  
  64.     }  
  65.       
  66.     public static class Count {  
  67.         private static int counter = 0;  
  68.         public static void incr(int x) {  
  69.             counter += x;  
  70.         }  
  71.         public static int get() {  
  72.             return counter;  
  73.         }  
  74.     }  
  75. }  

2. 输出结果:

 
  1. Thread-1 10 time  update oldValue : 14 , result : EXISTS  
  2. Test counter: 6  
  3. Thread-2 10 time  update oldValue : 14 , result : EXISTS  
  4. Test counter: 15  
  5. Thread-3 10 time  update oldValue : 17 , result : EXISTS  
  6. Test counter: 22  
  7. Thread-5 10 time  update oldValue : 17 , result : EXISTS  
  8. Test counter: 27  
  9. Thread-4 10 time  update oldValue : 20 , result : OK  
  10. Test counter: 33  
  11. Thread-8 10 time  update oldValue : 27 , result : OK  
  12. Test counter: 36  
  13. Thread-6 10 time  update oldValue : 28 , result : EXISTS  
  14. Test counter: 43  
  15. Thread-10 10 time  update oldValue : 31 , result : EXISTS  
  16. Test counter: 52  
  17. Thread-9 10 time  update oldValue : 31 , result : OK  
  18. Test counter: 60  
  19. Thread-7 10 time  update oldValue : 35 , result : OK  
  20. Test counter: 65  

3. 分析

我们可以看到,未成功的次数最终为65,数据值最终为35,两者的和刚好是100,正好符合我们的实验结果预期。

1. Memcached是什么?

Memcached是分布式的内存对象缓存系统。


2. Memcached的基本数据结构是什么?
Memcached是基于Key/Value对的HashMap。每一对,都可以设定过期时间。


3. Memcached用什么实现?
服务端程序由C语言编写,客户端可以用任何语言编写。客户端通过Memcached协议与服务端通信。


4. Memcached特点
(1)无备份/冗余:
各Memcached节点的数据之间没有互相备份,一旦某个节点挂掉,缓存中的数据就会丢失。


5. 开发团队
Memcached由Danga Interactive开发。


6. 相关下载
(1)Memcached服务端程序
http://memcached.org/


(2)Memcached的客户端程序
http://code.google.com/p/memcached/wiki/Clients


(3)Memcached可视化管理系统(PHP和jQuery编写)

http://www.junopen.com/memadmin


7. 如何理解Memcached的分布式特点?

Memcached Server并不具有分布式特征,每个Server都是独立运行的,各Server之间不存在通信获知其他节点状态和数据备份的功能。那么Memcached为什么还是分布式的缓存系统呢?其实说到Memcached的分布式,是将Memcached Client结合在一起考虑的。具体的分布式策略,由Client实现。也就是说Memcached的分布式,不是系统层的,而是应用层的。

在使用Memcached时,一般实时读写的场景并不多见。但多是Memcached写入后,在一定时间后才会有读操作。但是如果应用场景,是写入后瞬间即会有读操作呢?似乎没有什么特别之处,我们依然可以这样写:

注:此处使用的是spymemcached客户端。

  1. MemcachedClient cache = new MemcachedClient(cacheServerAddr);  
  2. cache.set("key"3600, bigData);  
  3. return cache.get("key");  
如此写入缓存后,如果立刻就有其他客户端进行读操作,则会读取失败,因为set是同步操作(sync),很可能仍还没有写入完。

一种可行的方法,是采用同步写操作。常用的set方法没有这种方式,需要采用遵守Memcached的CAS(Check And Set)协议的写操作。而这种写操作,一般是基于读取后得到CAS ID(类似于SVN中的版本ID),根据这个CAS ID来保证写入时,没有和其他写入操作产生“写重复”冲突。因此,在我们现在所讨论的场景中,可以如下使用CAS协议:

(1)初始写入:写一个简单的初始值;

(2)获取版本:使用异步方式获取CAS ID;

(3)同步写入:以同步方式写入数据,保证在读取前,已经写入结束。

 
  1. MemcachedClient cache = new MemcachedClient(cacheServerAddr);  
  2. cache.set(“key”, 3600"");  
  3. long casId = cache.asyncGets("key").get().getCas();  
  4. cache.cas("key", cased, bigData);  
  5. return cache.get("key");  

以这种“Set-Asyncgets-Cas”方式的缓存异步实时读写问题的解决方案,我们称之为“SAC”(你一定想到了什么??)。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值