|
Memcache(http://memcached.org/)主要用于实现分布式的Key-Value存储。
http://code.google.com/p/memcached/wiki/Clients
Java
spymemcached
·http://www.couchbase.org/code/couchbase/java
◦An improved Java API maintained by Matt Ingenthron and others at Couchbase.
◦Aggressively optimised, ability to run async, supports binary protocol, support Membase and Couchbase features, etc. See site for details.
Java memcached client
·http://www.whalin.com/memcached
◦A Java API is maintained by Greg Whalin from Meetup.com.
More Java memcached clients
·http://code.google.com/p/javamemcachedclient
·http://code.google.com/p/memcache-client-forjava
·http://code.google.com/p/xmemcached
Integrations
·http://code.google.com/p/simple-spring-memcached
·http://code.google.com/p/memcached-session-manager
Memcached-Java-Client
官方网址:https://github.com/gwhalin/Memcached-Java-Client
SVN:https://github.com/gwhalin/Memcached-Java-Client.git
ZZB:HOWTO:
=====
Basic Example:
==============
Lets say you have 3 servers. Server 1 and server 2 have 3GB of space
and server 3 has 2GB of space for cache. Here is how I would set up
my client.
import com.danga.MemCached.*;
public class MyClass {
// create a static client as most installs only need
// a single instance
protected static MemCachedClient mcc = new MemCachedClient();
// set up connection pool once at class load
static {
// server list and weights
String[] servers =
{
"server1.mydomain.com:1624",
"server2.mydomain.com:1624",
"server3.mydomain.com:1624"
};
Integer[] weights = { 3, 3, 2 };
// grab an instance of our connection pool
SockIOPool pool = SockIOPool.getInstance();
// set the servers and the weights
pool.setServers( servers );
pool.setWeights( weights );
// set some basic pool settings
// 5 initial, 5 min, and 250 max conns
// and set the max idle time for a conn
// to 6 hours
pool.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 size
pool.setMaintSleep( 30 );
// set some TCP settings
// disable nagle
// set the read timeout to 3 secs
// and don't set a connect timeout
pool.setNagle( false );
pool.setSocketTO( 3000 );
pool.setSocketConnectTO( 0 );
// initialize the connection pool
pool.initialize();
// lets set some compression on for the client
// compress anything larger than 64k
mcc.setCompressEnable( true );
mcc.setCompressThreshold( 64 * 1024 );
}
// from here on down, you can call any of the client calls
public static void examples() {
mcc.set( "foo", "This is a test String" );
String bar = mcc.get( "foo" );
}
} | Multi-client Example:
=====================
If you need to support multiple clients (i.e. Java, PHP, Perl, etc.)
you need to make a few changes when you are setting things up:
// use a compatible hashing algorithm
pool.setHashingAlg( SockIOPool.NEW_COMPAT_HASH );
// store primitives as strings
// the java client serializes primitives
//
// note: this will not help you when it comes to
// storing non primitives
mcc.setPrimitiveAsString( true );
// don't url encode keys
// by default the java client url encodes keys
// to sanitize them so they will always work on the server
// however, other clients do not do this
mcc.setSanitizeKeys( false ); | Failover/Failback Notes:
========================
By default the java client will failover to a new server when a server
dies. It will also failback to the original if it detects that the
server comes back (it checks the server in a falling off pattern).
If you want to disable this (useful if you have flapping servers),
there are two settings to handle this.
pool.setFailover( false );
pool.setFailback( false );
Serialization:
==============
For java "native types", which include:
Boolean
Byte
String
Character
StringBuffer
StringBuilder
Short
Long
Double
Float
Date
Integer | The client will by default NOT use java serialization, and instead
will serialize using the primitive values to save space. You can
override this by using the mcc.setPrimitiveAsString( true ), which
will use the toString representation of the object.
For other java objects, you need to make sure the class implements
Serializable in order to be able to be stored in the cache.
I would also reccomend that if possible, classes should instead
implement Externalizable as opposed to Serializable. This allows the
author of the class to define how objects of that class should
serialize. In practice at Meetup.com, we saw a 60% reduction in the size
of our serialized objects by doing this. This means less data to eat up
cache space and less data to transfer over the network.
Other:
======
See the java docs.
Memcached-Java-Client 3.0.x
3.0.x released, features = 2.6.x, but you can now get it from maven central, please notice:
·since the domain danga.com is no more under our control(according to maven’s policy, the domain should be under authors’ control), the package name was replaced with “whalin.com”. If you don’t intend to rebuild your app, please use 2.6.×.
·search “com.whalin” or “memcached java client” in search.maven.org, and you will find 3.0.×.
http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22Memcached-Java-Client%22
http://www.infoq.com/cn/articles/memcached-java
缓存系统MemCached的Java客户端优化历程
Memcached命令详解
来源:http://blog.sina.com.cn/s/blog_5410860001010fx9.html
启动服务:
/usr/local/memcached/bin/memcached -h
memcached 1.4.8
-p <num> TCP port number to listen on (default: 11211)
-U <num> UDP port number to listen on (default: 11211, 0 is off)
-s <file> UNIX socket path to listen on (disables network support)
-a <mask> access mask for UNIX socket, in octal (default: 0700)
-l <addr> interface to listen on (default: INADDR_ANY, all addresses)
<addr> may be specified as host:port. If you don't specify
a port number, the value you specified with -p or -U is
used. You may specify multiple addresses separated by comma
or by using -l multiple times
-d run as a daemon
-r maximize core file limit
-u <username> assume identity of <username> (only when run as root)
-m <num> max memory to use for items in megabytes (default: 64 MB)
-M return error on memory exhausted (rather than removing items)
-c <num> max simultaneous connections (default: 1024)
-k lock down all paged memory. Note that there is a
limit on how much memory you may lock. Trying to
allocate more than that would fail, so be sure you
set the limit correctly for the user you started
the daemon with (not for -u <username> user;
under sh this is done with 'ulimit -S -l NUM_KB').
-v verbose (print errors/warnings while in event loop)
-vv very verbose (also print client commands/reponses)
-vvv extremely verbose (also print internal state transitions)
-h print this help and exit
-i print memcached and libevent license
-P <file> save PID in <file>, only used with -d option
-f <factor> chunk size growth factor (default: 1.25)
-n <bytes> minimum space allocated for key+value+flags (default: 48)
-L Try to use large memory pages (if available). Increasing
the memory page size could reduce the number of TLB misses
and improve the performance. In order to get large pages
from the OS, memcached will allocate the total item-cache
in one large chunk.
-D <char> Use <char> as the delimiter between key prefixes and IDs.
This is used for per-prefix stats reporting. The default is
":" (colon). If this option is specified, stats collection
is turned on automatically; if not, then it may be turned on
by sending the "stats detail on" command to the server.
-t <num> number of threads to use (default: 4)
-R Maximum number of requests per event, limits the number of
requests process for a given connection to prevent
starvation (default: 20)
-C Disable use of CAS
-b Set the backlog queue limit (default: 1024)
-B Binding protocol - one of ascii, binary, or auto (default)
-I Override the size of each slab page. Adjusts max item size
(default: 1mb, min: 1k, max: 128m)
-o Comma separated list of extended or experimental options
- (EXPERIMENTAL) maxconns_fast: immediately close new
connections if over maxconns limit
- hashpower: An integer multiplier for how large the hash
table should be. Can be grown at runtime if not big enough.
Set this based on "STAT hash_power_level" before a
restart.
/usr/local/memcached/bin/memcached -d start -u root -m 2048 -l 127.0.0.1 -P /tmp/memcached.pid
停止memcached服务:
kill `cat /tmp/memcached.pid`
用telnet 127.0.0.1 11211连接到memcached服务器
memcached命令
标准协议
No Reply
存储命令
set命令
add命令
replace命令
append命令
prepend命令
cas命令
读取命令
get命令
gets命令
删除命令
incr/decr命令
查看memcached使用状态
stats命令
stats items命令
stats slabs命令
stats sizes命令
flush_all命令
全部协议在Protocol Documentation中
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
标准协议
memcached所有的标准协议包含在对item执行命令过程中,一个item包含:
一个key
一个32位的标志值
以秒为单位的失效时间
一个64为的CAS值,这个是唯一的
数据
CAS是可选的,可以使用“
-C
”禁止CAS。
No Reply
大多数ascii命令允许“noreply”。建议大家在ascii协议下别用“noreply”,因为那样不会报请求错误。“noreply”的目的是在执行交互命令(如:set、add)后,避免等待返回的包。
二进制协议将“noreply”定义为声明。如果你的客户端支持或者使用二进制协议,那么你将会用到它。
--------------------------------------------------------------------------------
(本文出自php_sir的新浪博客,用户名php_sir,首页链接:http://blog.sina.com.cn/phpsir,未经本人(php_sir)同意禁止转载)
存储命令
首先客户端向服务器按照如下格式发送命令行:
<command name> <key> <flags> <exptime> <bytes>rn
a) <command name> 可以是"set", "add", "replace"。
"set"表示按照相应的<key>存储该数据。
"add"表示按照相应的<key>添加该数据,但是如果该<key>已经存在则会操作失败。
"replace"表示按照相应的<key>替换数据,但是如果该<key>不存在则操作失败
b) <key> 客户端需要保存数据的key。
c) <flags> 是一个16位的无符号的整数(以十进制的方式表示)。该标志将和需要存储的数据一起存储,并在客户端get数据时返回。客户可以将此标志用做特殊用途,此标志对服务器来说是不透明的。
d) <exptime> 过期的时间。如果该数值为0表示存储的数据永远不过时(但是,该数据有可能被其他项所替换掉。因为服务器采用了LRU(最近最久没有使用)的算法替换)。如果非0(unix时间或者距离此时的秒数),当过期后,服务器可以保证用户得不到该数据(以服务器时间为标准)。
e) <bytes> 需要存储的字节数(不包含最后的"rn"),当用户希望存储空数据时,<bytes>可以为0
f) 最后客户端需要加上"rn"作为"命令头"的结束标志。
<data block>rn
紧接着"命令头"结束之后就要发送数据块(即希望存储的数据内容),最后加上"rn"作为此次通讯的结束。
reply
当以上数据发送结束之后,服务器将返回一个应答。可能有如下的情况:
a) "STOREDrn"
表示存储成功
b) "NOT_STOREDrn"
表示存储失败,但是该失败不是由于错误。通常这是由于"add"或者"replace"命令本身的要求所引起的,或者该项在删除队列之中(见delete命令)。
set
set是保存数据命令。会覆盖已存在的数据,而新数据将在LRU顶端
add
只有在该数据不存在时才保存该数据。如果是新加入的item,那么将其直接放在LRU顶端;如果item已经存在导致add失败,那么将这个item从LRU链表上摘下再放到LRU顶端。
replace
替换已经存在的数据。 这个操作几乎用不到。
append
紧接着已经存在的item增加item。这个操作不允许增加原来的item限制,对管理链表很有用。
prepend
与append命令类似,这个命令是在已存在的数据前加入新数据。
cas
检查并存储(
Check And Set)或者比较并更新(Compare And Swap)。如果从上次读取到现在没有更新,那么存入数据,处理更新竞争很有用。
--------------------------------------------------------------------------------
读取命令
获取数据的格式:
get <key>*rn
a) <key>* 表示一个或者多个key(以空格分开)
b) "rn" 命令头的结束
reply
服务器端将返回0个或者多个的数据项。每个数据项都是由一个文本行和一个数据块组成。当所有的数据项都接收完毕将收到"ENDrn"
每一项的数据结构:
VALUE <key> <flags> <bytes>rn
<data block>rn
a) <key> 希望得到存储数据的key
b) <falg> 发送set命令时设置的标志项
c) <bytes> 发送数据块的长度(不包含"rn")
d) "rn" 文本行的结束标志
e) <data block> 希望接收的数据项。
f) "rn" 接收一个数据项的结束标志。
如果有些key出现在get命令行中但是没有返回相应的数据,这意味着服务器中不存在这些项,这些项过时了,或者被删除了。
get
读取命令, 更具一个或多个key查找数据,并返回所找到的数据。
gets
使用CAS的get命令,返回的item带有一个CAS标识符 (一个唯一的64位数)。使用cas命令返回数据。如果得到的item的cas值被更改了,这个数据将不会被保存。
--------------------------------------------------------------------------------
删除命令
如果存在,将item从cache中删除,
delete 命令格式:
delete <key> <time>rn
a) <key> 需要被删除数据的key
b) <time> 客户端希望服务器将该数据删除的时间(unix时间或者从现在开始的秒数)
c) "rn" 命令头的结束
reply
a) "DELETEDrn" 删除成功
b) "NOT_FOUNDrn" 需要删除的key不存在
--------------------------------------------------------------------------------
incr/decr
Increment and Decrement. 如果item是以64为整型存储的,那么可以使用incr和decr命令修改那个数。
如果数据不存在,那么将返回失败。
命令格式:
incr <key> <value>rn
or
decr <key> <value>rn
a) <key> 数据项的key
b) <value> 用户希望增加/减少的数据的数值.该数值是一个32位十进制的无符号整形变量。
c) "rn" 命令行结束标志
reply
a) "NOT_FOUNDrn" 没有找到需要操作的项。
b) "<value>rn" <value>数据项有效期的最新剩余时间。
注意:
a) 如果一个数据项的有效期被设置为0,这时使用decr命令是无法减少数据。
b) 如果要执行 incr key -1 的操作不会有什么问题,结果和你希望的一样。但是,执行decr -1时的结果一定会让你觉得很意外,因为它的结果无论key的数据是什么结果的都是0.原因是:在这两个命令的执行过程中都是吧-1当做一个无符号的整形处理的。
c) 执行decr命令时数据的长度不会随之而减小,而是在返回数据的后面填补空格。但是执行incr命令越界后会自动的增加数据的位数。
--------------------------------------------------------------------------------
查看memcached使用状态
通过这些命令可以查看memcached服务器的使用状态。
stats
查看memcached状态的基本命令,通过这个命令可以看到如下信息:
STAT pid 22459 进程ID
STAT uptime 1027046 服务器运行秒数
STAT time 1273043062 服务器当前unix时间戳
STAT version 1.4.4 服务器版本
STAT pointer_size 64 操作系统字大小(这台服务器是64位的)
STAT rusage_user 0.040000 进程累计用户时间
STAT rusage_system 0.260000 进程累计系统时间
STAT curr_connections 10 当前打开连接数
STAT total_connections 82 曾打开的连接总数
STAT connection_structures 13 服务器分配的连接结构数
STAT cmd_get 54 执行get命令总数
STAT cmd_set 34 执行set命令总数
STAT cmd_flush 3 指向flush_all命令总数
STAT get_hits 9 get命中次数
STAT get_misses 45 get未命中次数
STAT delete_misses 5 delete未命中次数
STAT delete_hits 1 delete命中次数
STAT incr_misses 0 incr未命中次数
STAT incr_hits 0 incr命中次数
STAT decr_misses 0 decr未命中次数
STAT decr_hits 0 decr命中次数
STAT cas_misses 0 cas未命中次数
STAT cas_hits 0 cas命中次数
STAT cas_badval 0 使用擦拭次数
STAT auth_cmds 0
STAT auth_errors 0
STAT bytes_read 15785 读取字节总数
STAT bytes_written 15222 写入字节总数
STAT limit_maxbytes 1048576 分配的内存数(字节)
STAT accepting_conns 1 目前接受的链接数
STAT listen_disabled_num 0
STAT threads 4 线程数
STAT conn_yields 0
STAT bytes 0 存储item字节数
STAT curr_items 0 item个数
STAT total_items 34 item总数
STAT evictions 0 为获取空间删除item的总数
stats items
输出各个slab中的item信息。s
stats slabs
输出slab中更详细的item信息
stats sizes
输出所有item的大小和个数
stats cachedump <slab_id> <limit_num>
根据<slab_id>输出相同的<slab_id>中的item信息。<limit_num>是输出的个数,当<limit_num>为0是输出所有的item。
--------------------------------------------------------------------------------
flush_all
使在内存中所有的item失效。加入参数则表示在N秒后失效所有item。这项操作会立即返回,不会暂停服务器。这个操作并不会真的释放内存空间,而是标志所有的item为失效
Memcached 协议中英文对照:http://blog.s135.com/book/memcached/
STAT curr_items Current number of items stored by the server 表示当前缓存中存放的所有缓存对象的数量。不包括目前已经从缓存中删除的对象。
STAT total_items Total number of items stored by this server ever since it started 表示从memcached服务启动到当前时间,系统存储过的所有对象的数量,包括目前已经从缓存中删除的对象。
API文档:
com.danga.MemCached.MemCachedClient http://www.geelou.com/javadocs/java_memcached-release_2.0.1/com/danga/MemCached/MemCachedClient.html
net.spy.memcached.MemcachedClient http://dustin.github.io/java-memcached-client/apidocs/net/spy/memcached/MemcachedClient.html
memcached storeCounter/getCounter计数器 http://blog.163.com/chenyuan_208/blog/static/1976481862012611112750951/
memcached 最大连接数设置
http://hi.baidu.com/jifeer/item/2065cb6ab46a7b3fac3e83b2
由于客户端设置连接数过多,经常有超时现象,把服务器改为 2048 ,试试好些不.
经测试,的确好的多了. 但是估计还不够, 再增加到30720看看,每个 10240个
----------------------------------------------引用-------------------------------------------------
memcached的基本设置:
-p 监听的端口
-l 连接的IP地址, 默认是本机
-d start 启动memcached服务
-d restart 重起memcached服务
-d stop|shutdown 关闭正在运行的memcached服务
-d install 安装memcached服务
-d uninstall 卸载memcached服务
-u 以的身份运行 (仅在以root运行的时候有效)
-m 最大内存使用,单位MB。默认64MB
-M 内存耗尽时返回错误,而不是删除项
-c 最大同时连接数,默认是1024
-f 块大小增长因子,默认是1.25
-n 最小分配空间,key+value+flags默认是48
-h 显示帮助
mixi的设置,单台:
每台memcached服务器仅启动一个memcached进程。分配给memcached的内存为3GB,启动参数如下:
/usr/bin/memcached -p 11211 -u nobody -m 3000 -c 30720 |
|