微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!
memcached client --ref
Clients  Client API's / librariesUpdated Jul 14, 2012 by [email protected]:https://code.google.com/p/memcached/wiki/ClientsC / C++libmemcachedhttp://libmemcached.org/ by Brian Aker, Commercial Support available from Data DifferentialBSD license, it has been in production at websites for years. Aggressively optimised, ability to run async, supports binary protocol, triggers, replica, etc. libmemcachehttp://people.freebsd.org/~seanc/libmemcache by Sean ChittendenBSD license. It is no longer under active development (last updated in 2006). You should try libmemcached instead. apr_memcachehttp://www.outoforder.cc/projects/libs/apr_memcache by Paul QuernaApache Software License version 2.0 (doesn't appear to be actively maintained since 2005) memcacheclienthttp://code.jellycan.com/memcacheclient (cross-platform, but primary focus on Windows (last updated in 2008). libketamahttp://www.last.fm/user/RJ/journal/2007/04/10/rz_libketama (the original consistent hashing algorithm from last.fm) PHPComparison of PECL/memcache and PECL/memcachedPECL/memcachedhttp://pecl.php.net/package/memcached (wraps libmemcached)pear install pecl/memcachedAnnouncement: http://gravitonic.com/2009/01/new-memcached-extension PECL/memcachehttp://pecl.php.net/package/memcachephp memcached docs PHP libmemcachedhttp://github.com/kajidai/php-libmemcached/tree/master (wraps libmemcached) Javaspymemcachedhttp://www.couchbase.org/code/couchbase/javaAn 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 clienthttp://www.whalin.com/memcachedA Java API is maintained by Greg Whalin from Meetup.com. More Java memcached clientshttp://code.google.com/p/javamemcachedclienthttp://code.google.com/p/memcache-client-forjavahttp://code.google.com/p/xmemcached Integrationshttp://code.google.com/p/simple-spring-memcachedhttp://code.google.com/p/memcached-session-manager Pythonpylibmc - a libmemcached wrapperhttp://sendapatch.se/projects/pylibmc/ python-memcachedhttp://www.tummy.com/Community/software/python-memcached/ pooling wrapper classhttp://jehiah.cz/download/MemcachePool.py.txt for use in multi-threaded applications Python libmemcachedhttp://code.google.com/p/python-libmemcached (libmemcached wrapper) Python-Binary-Memcached - binprot pure-python clienthttps://github.com/jaysonsantos/python-binary-memcached cmemcache (Note: this library is deprecated, old, buggy, you should not use it).http://gijsbert.org/cmemcache/index.html Django's caching framework works with memcachedhttp://docs.djangoproject.com/en/dev/topics/cache/ Twisted python clienthttp://python.net/crew/mwh/apidocs/twisted.protocols.memcache.html Rubycache_fu Rails plugin works with memcachedhttp://github.com/defunkt/cache_fu/tree/masterhttp://errtheblog.com/posts/57-kickin-ass-w-cachefuhttp://blog.onmylist.com/articles/2007/06/15/memcached-and-cache_fu memcache-clienthttp://dev.robotcoop.com/Libraries/memcache-client/index.html (pure Ruby)http://seattlerb.rubyforge.org/memcache-client/http://www.freshports.org/databases/rubygem-memcache-client Ruby-MemCachehttp://www.deveiate.org/projects/RMemCache (pure Ruby) faunahttp://blog.evanweaver.com/files/doc/fauna/memcached (compiled, wraps libmemcached) caffeinehttp://rubyforge.org/projects/adocca-plugins (compiled, wraps libmemcached, no license) More info:Memcached basics for railsRails and memcached while developing your app PerlCache::Memcachedhttp://search.cpan.org/dist/Cache-Memcached Cache::Memcached::Fasthttp://search.cpan.org/dist/Cache-Memcached-Fast Perl libmemcached wrapperhttp://code.google.com/p/perl-libmemcached (libmemcached wrapper) Cache::Memcached-compatible perl libmemcached wrapper wrapper (heh)http://search.cpan.org/dist/Cache-Memcached-libmemcached/ Windows / .NET.Net memcached clienthttps://sourceforge.net/projects/memcacheddotnet .Net 2.0 memcached clienthttp://www.codeplex.com/EnyimMemcachedClient developed in .NET 2.0 keeping performance and extensibility in mind. (Supports consistent hashing.)http://www.codeplex.com/memcachedproviders BeIT Memcached Client (optimized C# 2.0)http://code.google.com/p/beitmemcached jehiahhttp://jehiah.cz/projects/memcached-win32 MySQLMySQL user data functions for memcachedhttps://launchpad.net/memcached-udfs MySQL Engineno longer developed PostgreSQLpgmemcachehttp://pgfoundry.org/projects/pgmemcache The pgmemcache project allows you to access memcache servers from Postgresql Stored Procedures and Triggers. Erlangerlmchttp://github.com/JacobVorreuter/erlmchttp://jacobvorreuter.com/erlang-binary-protocol-memcached-client merlemerle, an erlang memcached client erlangmchttp://code.google.com/p/erlangmc higepon's memcached clienthttp://github.com/higepon/memcached-client Zhou Li's memcached clienthttp://github.com/echou/memcached-client https://github.com/EchoTeam/mcdLuahttp://luamemcached.luaforge.netLisp dialectshttp://common-lisp.net/project/cl-memcachedhttp://chicken.wiki.br/memcachedhttp://weblambda.blogspot.com/2
How-to Dump Keys from Memcache--reference
Submitted by Lars Windolf on 19. October 2012 - 21:53http://lzone.de/dump%20memcache%20keysYou spent already 50GB on the memcache cluster, but you still see many evictions and the cache hit ratio doesn't look good since a few days. The developers swear that they didn't change the caching recently, they checked the code twice and have found no problem.What now? How to get some insight into the black box of memcached? One way would be to add logging to the application to see and count what is being read and written and then to guess from this about the cache efficiency. For to debug what's happening we need to set how the cache keys are used by the application.An Easier WayMemcache itself provides a means to peek into its content. The memcache protocol provides commands to peek into the data that is organized by slabs (categories of data of a given size range). There are some significant limitations though:You can only dump keys per slab class (keys with roughly the same content size)You can only dump one page per slab class (1MB of data)This is an unofficial feature that might be removed anytime.The second limitation is propably the hardest because 1MB of several gigabytes is almost nothing. Still it can be useful to watch how you use a subset of your keys. But this might depend on your use case.If you don't care about the technical details just skip to the tools section to learn about what tools allow you to easily dump everything. Alternatively follow the following guide and try the commands using telnet against your memcached setup.How it WorksFirst you need to know how memcache organizes its memory. If you start memcache with option "-vv" you see the slab classes it creates. For example$ memcached -vvslab class 1: chunk size 96 perslab 10922slab class 2: chunk size 120 perslab 8738slab class 3: chunk size 152 perslab 6898slab class 4: chunk size 192 perslab 5461[...]In the configuration printed above memcache will keep fit 6898 pieces of data between 121 and 152 byte in a single slab of 1MB size (6898*152). All slabs are sized as 1MB per default. Use the following command to print all currently existing slabs:stats slabsIf you've added a single key to an empty memcached 1.4.13 withset mykey 0 60 11STOREDyou'll now see the following result for the "stats slabs" command:stats slabsSTAT 1:chunk_size 96STAT 1:chunks_per_page 10922STAT 1:total_pages 1STAT 1:total_chunks 10922STAT 1:used_chunks 1STAT 1:free_chunks 0STAT 1:free_chunks_end 10921STAT 1:mem_requested 71STAT 1:get_hits 0STAT 1:cmd_set 2STAT 1:delete_hits 0STAT 1:incr_hits 0STAT 1:decr_hits 0STAT 1:cas_hits 0STAT 1:cas_badval 0STAT 1:touch_hits 0STAT active_slabs 1STAT total_malloced 1048512ENDThe example shows that we have only one active slab type #1. Our key being just one byte large fits into this as the smallest possible chunk size. The slab statistics show that currently on one page of the slab class exists and that only one chunk is used.Most importantly it shows a counter for each write operation (set, incr, decr, cas, touch) and one for gets. Using those you can determine a hit ratio!You can also fetch another set of infos using "stats items" with interesting counters concerning evictions and out of memory counters.stats itemsSTAT items:1:number 1STAT items:1:age 4STAT items:1:evicted 0STAT items:1:evicted_nonzero 0STAT items:1:evicted_time 0STAT items:1:outofmemory 0STAT items:1:tailrepairs 0STAT items:1:reclaimed 0STAT items:1:expired_unfetched 0STAT items:1:evicted_unfetched 0ENDWhat We Can Guess Already...Given the statistics infos per slabs class we can already guess a lot of thing about the application behaviour:How is the cache ratio for different content sizes?How good is the caching of large HTML chunks?How much memory do we spend on different content sizes?How much do we spend on simple numeric counters?How much do we spend on our session data?How much do we spend on large HTML chunks?How many large objects can we cache at all?Of course to answer the questions you need to know about the cache objects of your application.Now: How to Dump Keys?Keys can be dumped per slabs class using the "stats cachedump" command.stats cachedump <slab class> <number of items to dump>To dump our single key in class #1 runstats cachedump 1 1000ITEM mykey [1 b; 1350677968 s]ENDThe "cachedump" returns one item per line. The first number in the braces gives the size in bytes, the second the timestamp of the creation. Given the key name you can now also dump its value usingget mykeyVALUE mykey 0 11ENDThis is it: iterate over all slabs classes you want, extract the key names and if need dump there contents.Dumping ToolsThere are different dumping tools sometimes just scripts out there that help you with printing memcache keys:PHPsimple scriptPrints key names.Perlsimple scriptPrints keys and valuesRubysimple scriptPrints key names.PerlmemdumpTool in CPAN module Memcached-libmemcachedPHPmemcache.phpMemcache Monitoring GUI that also allows dumping keyslibmemc
Memcached source code analysis -- Analysis of change of state--reference
This article mainly introduces the process of Memcached, libevent structure of the main thread and worker thread based on the processing of the connection state of mutual conversion (not involving data access operations), the main business logic is the drive_machine. State transition process does not involve all the state, at the same time, because of his ability, some state transition may be wrong, also please predecessors. Conversion conditions: TCP, ASCII protocol. (not including conn_swallow, binary protocols will use this state)1 OverviewFirst introduces the connection, connection is connected to the conn Memcached definition of their own. All state, drive_machine () is the main conversion of the state of operation:enum conn_states { conn_listening, /**<the socket which listens for connections /The main thread waits on the link*/ conn_new_cmd, /**<Prepare connection for next command /workerThreads are waiting for the command*/ conn_waiting, /**<waiting for a readable socket /workerThe thread is waitingsdfA readable information*/ conn_read, /**<reading in a command line /workerThread the read command*/ conn_parse_cmd, /**<try to parse a command from the input buffer /wokerThread*/ conn_write, /**<writing out a simple response /workerThread*/ conn_nread, /**<reading in a fixed number of bytes /workerBecause the command finished thread, Continue to read / conn_swallow, /**<swallowing unnecessary bytes w/o storing /worker thread, ASCIIThe agreement is not involved in this state*/ conn_closing, /**<closing this connection */ conn_mwrite, /**<writing out many items sequentially /workerThread, The response content to * / conn_max_state /**<Max state value (used for assertion) / marker for conn_states boundary, Beyond that states is wrong*/ };In the Memcached.c (main), the main thread and worker thread to complete the necessary initialization, bind the corresponding libevent events, then the main thread monitor bind monitoring ports, do a good job recycling for formal. Below is the total conversion connection state graph.2 receive connections are distributed to the worker thread The main thread initialization, connecting into conn_listening state, waiting for the connection.When there is a connection, the main thread through the dispatch_conn_new () to pipeline writes characters C, connect the distributed to a worker thread worker thread connection, receive, enter the conn_new_cmd wait state.3 data readConn_new_cmd is waiting for the new connection, when the connection is written, if the current request too many, may cause starvation on other worker threads, change event type is EV_WRITE, exit.If the connection is not much, and have not read data, shows the pending command, a trip to the conn_parse_cmd, in order to continue processing the command.If the connection is not much, and is a new connection, showed no unread data, is connected into the conn_waiting state waiting for data (command).conn_waiting, Threads are waiting for subsequent data connection, if a data set to the current socket FD for reading EV_READ, ensure the following content of reading. In conn_read, call try_read_network () to read from socket FD, if no data is returned to conn_waiting, if the data is entered into the conn_parse_cmd, waiting for processing command.The 4 command parsingAfter entering the conn_parse_cmd, received the order, call try_read_command () to analyze the user command, this analysis of the ASCII protocol commands, which can call process_command () to handle user command.According to the user's command, will call for different types of orders. Such as set, replace, update_command); incr (command corresponds, decr corresponds to process_arithmetic_command (gets); process_get_command (corresponding) etc.If the update type command, also need to read the updated content, enter the conn_nread state.Other types of command has to wait for the results.The 5 command returnsThere will be in response to a command execution, if the command only need feedback an execution results, through the out_string () function to output the results, enter conn_write.If the get command, you need to print the contents of get, into the conn_mwrite stage.The case statement conn_write without break, so the normal print will be going to conn_mwrite.The 6 result outputConn_mwrite, call transmit () the response results are output. Transmit () to check the current state of the writing.If the data is finished, then change the state of waiting for the new command is conn_new_cmd.If not finished, then continue to wait, until finished.7 SummaryAbove is the conversion and connection status, analysis is not in place or wrong place please. In general, feel the Memcached application of libevent writes very standard, follow up with libevent, but also can learn from Memcached to a lot of knowledge.reference from:http://www.programering.com/a/MzM3MjMwATU.html
Memcached source code analysis (threading model)--reference
Look under the start memcahced threading process memcached multi-threaded mainly by instantiating multiple libevent, are a main thread and n workers thread is the main thread or workers thread all through the the libevent management network event, in fact, each thread is a separate libevent instance The main thread is responsible for monitoring the client to establish a connection request and accept connections workers thread to handle events such as read and write has established good connections Look at general icon: First look main data structures (thread.c): C code/ * An item in the connection queue. * /   typedef   struct conn_queue_item CQ_ITEM;struct conn_queue_item {int sfd out of the;int init_state;The int event_flags;int read_buffer_size;int is_udp;CQ_ITEM * next;};CQ_ITEM is actually the main thread accept returned package to establish a connection fd C code/ * A connection queue. * /   typedef   struct conn_queue CQ;struct conn_queue {CQ_ITEM * head;CQ_ITEM * tail;pthread_mutex_t lock;pthread_cond_t cond;};CQ is a CQ_ITEM the singly linked list C codetypedef   struct {pthread_t thread_id; / * unique ID of this thread * /   struct event_base * base; / * libevent handle this thread uses * /   struct event notify_event; / * listen event for notify pipe * /   int notify_receive_fd; / * receiving end of notify pipe * /   int notify_send_fd; / * sending end of notify pipe * /   CQ new_conn_queue; / * queue of new connections to handle * /   } LIBEVENT_THREAD;Memcached thread structure package, you can see each thread contains a CQ queue, a notification pipe pipe The instance event_base and a libevent Another important structure is the most important for each network connection Package conn C codetypedef   struct {int sfd out of the;int State;struct event event;short which;The char * RBUF;... / / Eliminating the status flag and read-write buf information   } Conn;memcached mainly through Settings / conversion connected to different states to handle the event (core function drive_machine) See next thread initialization process: The main function of the memcached.c, first initialized on the main thread libevent C code/ * Initialize main thread libevent instance * /   main_base = event_init ();Then initialize all workers thread and start the startup process will be described in detail later C code/ * Start up worker threads if MT mode * /   thread_init (settings.num_threads, main_base);Then the main thread calls (only analyze the the tcp situation, memcached support udp) C codeserver_socket (settings.port, 0)This method encapsulates create listening socket bound address, set the non-blocking mode and register the listening socket the libevent read event, a series of operations Then the main thread calls C code/ * Enter the event loop * /   event_base_loop (main_base, 0);At this time the main thread start libevent to accept the the external connection request, the entire start-up process is completed Let's look at how to start thread_init all workers thread, look at the core code thread_init C codevoid thread_init (int nthreads, struct event_base * main_base) {/ /. . . Omission   threads = malloc (sizeof (LIBEVENT_THREAD) * nthreads);if (threads) {perror ("Can't allocate thread descriptors");Exit (1);}  threads [0]. base = main_base;threads [0]. thread_id = pthread_self ();  for (i = 0; i <nthreads; i + +) {int fds [2];if (pipe (fds)) {perror ("Can't create notify pipe");Exit (1);}  threads [i notify_receive_fd = fds [0];threads [i]. notify_send_fd = the FDS [1];  setup_thread (& threads [i]);}  / * Create threads after we've done all the libevent setup. * /   for (i = 1; i <nthreads; i + +) {create_worker (worker_libevent, & threads [i]);}}threads statement static LIBEVENT_THREAD * threads; The thread_init first malloc thread space, and then the first threads as the main thread, the rest are workers thread is then created for each thread a pipe, this pipe is used as the main thread to inform the workers thread a new connection arrives Following setup_thread for C codestatic   void setup_thread (LIBEVENT_THREAD * me) {if (! me-> base) {me-> base = event_init ();if (! me-> base) {fprintf (stderr, "Can't allocate event base n");Exit (1);}}  / * Listen for notifications from other threads * /   event_set (& me-> notify_event, me-> notify_receive_fd,EV_READ | EV_PERSIST, thread_libevent_process, me);event_base_set (me-> base, & me-> notify_event);  if (event_add (& me-> notify_event, 0) == -1) {fprintf (stderr, "Can't monitor libevent notify pipe n");Exit (1);}  cq_init (& me-> new_conn_queue);}the create setup_thread libevent instance of all workers thread (the libevent main thread instance has been established in the main function) Since the threads before [0] base = main_base; first thread (the main thread) will not be here execution event_init () In this method, then is to register all workers thread pipe read end the libevent of read events, wait for the main thread last all workers CQ initialization the creat
Memcache及telnent命令详解--转
1、启动Memcache 常用参数memcached 1.4.3-p <num>      设置端口号(默认不设置为: 11211)-U <num>      UDP监听端口 (默认: 11211, 0 时关闭)  -l <ip_addr>  绑定地址 (默认:所有都允许,无论内外网或者本机更换IP,有安全隐患,若设置为127.0.0.1就只能本机访问)-d            duli进程运行-u <username> 绑定使用指定用于运行进程 <username>-m <num>      允许最大内存用量,单位M (默认: 64 MB)-P <file>     将PID写入文件<file>,这样可以使得后边进行快速进程终止, 需要与 -d 一起使用如:在linux下:./usr/local/bin/memcached -d -u jb-mc -l 192.168.1.197 -m 2048 -p 12121在window下:d:App_Servmemcachedmemcached.exe -d RunService -l 127.0.0.1 -p 11211 -m 500在windows下注册为服务后运行:sc.exe create jb-Memcached binpath= “d:App_Servmemcachedmemcached.exe -d RunService -p 11211 -m 500″ start= autonet start jb-Memcached2、telnet连接telnet 127.0.0.1 112113、写入memcache3.1 memcached Telnet Interface CommandDescriptionExamplegetReads a valueget mykeysetSet a key unconditionallyset mykey 0 60 5addAdd a new keyadd newkey 0 60 5replaceOverwrite existing keyreplace key 0 60 5appendAppend data to existing keyappend key 0 60 15prependPrepend data to existing keyprepend key 0 60 15incrIncrements numerical key value by given numberincr mykey 2decrDecrements numerical key value by given numberdecr mykey 5deleteDeletes an existing keydelete mykeyflush_allInvalidate specific items immediatelyflush_allInvalidate all items in n secondsflush_all 900statsPrints general statisticsstatsPrints memory statisticsstats slabsPrints memory statisticsstats mallocPrint higher level allocation statisticsstats items stats detail stats sizesResets statisticsstats resetversionPrints server version.versionverbosityIncreases log levelverbosityquitTerminate telnet sessionquit  3.2 telnet请求命令格式<command name> <key> <flags> <exptime> <bytes>rn <data block>rna) <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>可以为0f) 最后客户端需要加上”rn”作为”命令头”的结束标志。<data block>rn紧接着”命令头”结束之后就要发送数据块(即希望存储的数据内容),最后加上”rn”作为此次通讯的结束。3.3 telnet响应命令结果响应:reply当以上数据发送结束之后,服务器将返回一个应答。可能有如下的情况:a) “STOREDrn”:表示存储成功b) “NOT_STOREDrn” : 表示存储失败,但是该失败不是由于错误。通常这是由于”add”或者”replace”命令本身的要求所引起的,或者该项在删除队列之中。如: set key 33 0 4rnffffrn4、获取/检查KeyValueget <key>*rna) <key>* 表示一个或者多个key(以空格分开)b) “rn” 命令头的结束结果响应:reply服务器端将返回0个或者多个的数据项。每个数据项都是由一个文本行和一个数据块组成。当所有的数据项都接收完毕将收到”ENDrn”每一项的数据结构:VALUE <key> <flags> <bytes>rn<data block>rna) <key> 希望得到存储数据的keyb) <falg> 发送set命令时设置的标志项c) <bytes> 发送数据块的长度(不包含”rn”)d) “rn” 文本行的结束标志e) <data block> 希望接收的数据项。f) “rn” 接收一个数据项的结束标志。如果有些key出现在get命令行中但是没有返回相应的数据,这意味着服务器中不存在这些项,这些项过时了,或者被删除了如:get aaVALUE aa 33 4ffffEND5、删除KeyValue:delete <key> <time>rna) <key> 需要被删除数据的keyb) <time> 客户端希望服务器将该数据删除的时间(unix时间或者从现在开始的秒数)c) “rn” 命令头的结束6、检查Memcache服务器状态:statsrn在这里可以看到memcache的获取次数,当前连接数,写入次数,已经命中率等;pid : 进程iduptime :总的运行时间,秒数time : 当前时间version : 版本号……curr_items : 当前缓存中的KeyValue数量total_items : 曾经总共经过缓存的KeyValue数量bytes : 所有的缓存使用的内存量curr_connections 当前连接数….cmd_get : 总获取次数cmd_set : 总的写入次数get_hits : 总的命中次数miss_hits :  获取失败次数…..bytes_read : 总共读取的流量字节数bytes_written : 总的写入流量字节limit_maxbytes : 最大允许使用的内存量,字节7、高级缓存细节查看方法:stats reset清空统计数据stats malloc显示内存分配数据stats cachedump slab_id limit_num显示某个slab中的前limit_num个key列表,显示格式如下ITEM key_name [ value_length b; expire_time|access_time s]其中,memcached 1.2.2及以前版本显示的是  访问时间(timestamp)1.2.4以上版本,包括1.2.4显示 过期时间(timestamp)如果是永不过期的key,expire_time会显示为服务器启动的时间stats cachedump 7 2ITEM copy_test1 [250 b; 1207795754 s]ITEM copy_test [248 b; 1207793649 s]stats slabs显示各个slab的信息,包括chunk的大小、数目、使用情况等stats items显示各个slab中item的数目和最老item的年龄(最后一次访问距离现在的秒数)stats detail [on|off|dump]设置或者显示详细操作记录参数为on,打开详细操作记录参数为off,关闭详细操作记录参数为dump,显示详细操作记录(每一个键值get、set、hit、del的次数)8、清空所有键值flush_all注:flush并不会将items删除,只是将所有的items标记为expired,因此这时memcache依旧占用所有内存。9、退出quitrn 转自:http://blog.csdn.net/jinxingfeng_cn/article/details/24264693
Memcached Java Client with sample program--reference
In my previous post, I listed down most common telnet commands for memcached with sample execution terminal logs. Today I want to discuss about the Memcached Client program available in Java language.There are three most widely used memcached client programs in javaxmemcachedspymemcachedgwhalin memcached clientI have used Greg Whalin memcached client and found it easy to understand and use. It provides all the basic functionalities with thread pooling. Its available under BSD license and you can download it from below URL:https://github.com/gwhalin/Memcached-Java-ClientOnce you have downloaded the source code you can create a java project and copy all the java classes and then use it.To help you get started quickly, I am providing a sample program to showcase the usage of basic functions that can be performed with memcached server.package com.journaldev.memcached.test;import java.util.HashMap;import com.meetup.memcached.MemcachedClient;import com.meetup.memcached.SockIOPool;public class MemcachedJavaClient {/*** MemcachedJavaClient program to show the usage of different functions* that can be performed on Memcached server with Java Client* @param args*/public static void main(String[] args) {//initialize the SockIOPool that maintains the Memcached Server Connection PoolString[] servers = {"localhost:11111"};SockIOPool pool = SockIOPool.getInstance("Test1");pool.setServers( servers );pool.setFailover( true );pool.setInitConn( 10 );pool.setMinConn( 5 );pool.setMaxConn( 250 );pool.setMaintSleep( 30 );pool.setNagle( false );pool.setSocketTO( 3000 );pool.setAliveCheck( true );pool.initialize();//Get the Memcached Client from SockIOPool named Test1MemcachedClient mcc = new MemcachedClient("Test1");//add some value in cacheSystem.out.println("add status:"+mcc.add("1", "Original"));//Get value from cacheSystem.out.println("Get from Cache:"+mcc.get("1"));System.out.println("add status:"+mcc.add("1", "Modified"));System.out.println("Get from Cache:"+mcc.get("1"));//use set function to add/update value, use replace to update and not addSystem.out.println("set status:"+mcc.set("1","Modified"));System.out.println("Get from Cache after set:"+mcc.get("1"));//use delete function to delete key from cacheSystem.out.println("remove status:"+mcc.delete("1"));System.out.println("Get from Cache after delete:"+mcc.get("1"));//Use getMulti function to retrieve multiple keys values in one function// Its helpful in reducing network calls to 1mcc.set("2", "2");mcc.set("3", "3");mcc.set("4", "4");mcc.set("5", "5");String [] keys = {"1", "2","3","INVALID","5"};HashMap<String,Object> hm = (HashMap<String, Object>) mcc.getMulti(keys);for(String key : hm.keySet()){System.out.println("KEY:"+key+" VALUE:"+hm.get(key));}}}Output of the above program is:add status:trueGet from Cache:Originaladd status:falseGet from Cache:Originalset status:trueGet from Cache after set:Modifiedremove status:trueGet from Cache after delete:nullKEY:3 VALUE:3KEY:2 VALUE:2KEY:1 VALUE:nullKEY:INVALID VALUE:nullKEY:5 VALUE:5If you want to connect to multiple memcached servers then you will have to create multiple SockIOPool instances and then use the same name while getting the MemcacheClient instance. reference:http://www.journaldev.com/24/memcached-java-client-with-sample-program补充:memcachedclient获取方式有3中,上面是一种:MemcachedClientBuilder builder=new XMemcachedClientBuilder(AddrUtil.getAddresses("127.0.0.1:11211"));MemcachedClient memCacheClient=builder.build();------------------------------------------------------------MemcachedClient memcacheClient=new MemcachedClient(new InetSocketAddress("127.0.0.1:11211", 11211)); 
php和java的memcached使用的兼容性问题解决过程
1. 背景:php 使用memcached客户端设置一个key,java使用java-memcached-client去读,报错如下:ERROR|com.whalin.MemCached.MemCachedClient:-1|++++ exception thrown while trying to get object from cache for key: glt7hpcdi1ggo03l9qknu8a7552. 网上搜索,发现最多的解释: 在memcached中,不同的客户端在set或者add值时,对命令的第二个参数的使用是不一致的<command name> <key> <flags> <exptime> <bytes><data block>JAVA客户端flags字段填写的都是32,不是32的是无法通过java客户端get出来的所以在通过memcached admin进行数据set时,需要显示指定flags值为32set testkey 32 0 512345如此放入缓存后,通过java客户端是可以取出来的。 3. 可选的解决方案,1)从php端设置flag 2)从java端取的时候使用flag 3)使用别的客户端绕过这个障碍 。方案1,php端没有封装php的memcached客户端,调用在系统中随处可见,故该方案不可行,最起码风险比较大,成本高。方案2,研究了一下使用的memcached客户端,没法发现使用flag标示的地方,本身客户端如果自己去写的话,风险也不小。方案3,网上有人提到过使用spy memcached client可以避过,故尝试一下。4. 解决步骤:4.0. 增加spymemcached依赖            <dependency> <groupId>net.spy</groupId> <artifactId>spymemcached</artifactId> <version>2.12.0</version> </dependency>4.1. 配置memcached的ip地址   分别在dev,test,idc,prod的app-config.properties文件下添加memcached的ip地址:   dev,test:memcache_ip=192.168.1.10:11211  idc:memcache_ip=172.16.4.10:11211 prod:memcache_ip=172.16.0.10:11211 4.2. 配置memcached实例:app-cached.xml文件增加:<bean id="springContextHolder" class="com.test.bean.SpringContextHolder" /> <bean id="memcachedClient" class="net.spy.memcached.spring.MemcachedClientFactoryBean">      <property name="servers" value="${memcache_ip}"/>      <property name="protocol" value="BINARY"/>      <property name="transcoder">        <bean class="net.spy.memcached.transcoders.SerializingTranscoder">          <property name="compressionThreshold" value="1024"/>        </bean>      </property>      <property name="opTimeout" value="1000"/>      <property name="timeoutExceptionThreshold" value="1998"/>      <property name="useNagleAlgorithm" value="false"/>    </bean> 4.3. 新增类SpringContextHolderimport java.util.Map;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;/** *  * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext. **/public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; /** *  * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量. */ public void setApplicationContext(ApplicationContext applicationContext) { SpringContextHolder.applicationContext = applicationContext; } /** *  * 取得存储在静态变量中的ApplicationContext. */ public static ApplicationContext getApplicationContext() { checkApplicationContext(); return applicationContext; } /** *  * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { checkApplicationContext(); return (T) applicationContext.getBean(name); } /** *  * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. *  * 如果有多个Bean符合Class, 取出第一个. */ @SuppressWarnings("unchecked") public static <T> T getBean(Class<T> clazz) { checkApplicationContext(); Map beanMaps = applicationContext.getBeansOfType(clazz); if (beanMaps != null && !beanMaps.isEmpty()) { return (T) beanMaps.values().iterator().next(); } else { return null; } } private static void checkApplicationContext() { if (applicationContext == null) { throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder"); } }}4.4.增加MemcacheUtil import com.test.bean.SpringContextHolder;import net.spy.memcached.MemcachedClient;public class MemcacheUtil {    public static MemcachedClient getMemCachedClient() {        return SpringContextHolder.getBean("memcachedClient");}} 4.5 测试代码public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "classpath:spring-memcached-spy.xml"); MemcachedClient client=MemcacheUtil.getMemCachedClient();  //MemcachedClient client =(MemcachedClient)context.getBean("memcachedClient"); Object obj=client.get("glt7hpcdi1ggo03l9qknu8a755");  System.out.println(obj); } 注意事项:使用spy memcached客户端,在key-value对中,如果value是对象的话,则读取不到,是string的话则可以读取。故建议使用时key-value约定为string类型。value为对象的话,可以考虑转成json串。 
Memcache的问题集
o memcached是怎么工作的?o memcached最大的优势是什么?o memcached和MySQL的query cache相比,有什么优缺点?o memcached和服务器的local cache(比如PHP的APC、mmap文件等)相比,有什么优缺点?o memcached的cache机制是怎样的?o memcached如何实现冗余机制?       o memcached如何处理容错的?o 如何将memcached中item批量导入导出?o 但是我确实需要把memcached中的item都dump出来,确实需要把数据load到memcached中,怎么办?o memcached是如何做身份验证的?o 如何使用memcached的多线程是什么?如何使用它们?o memcached能接受的key的最大长度是多少?(250bytes)o memcached对item的过期时间有什么限制?(为什么有30天的限制?)o memcached最大能存储多大的单个item?(1M byte)o 为什么单个item的大小被限制在1M byte之内?o 为了让memcached更有效地使用服务器的内存,可以在各个服务器上配置大小不等的缓存空间吗?o 什么是binary协议?它值得关注吗?o memcached是如何分配内存的?为什么不用malloc/free!?究竟为什么使用slab呢?o memcached能保证数据存储的原子性吗?memcached是怎么工作的?Memcached的神奇来自两阶段哈希(two-stage hash)。Memcached就像一个巨大的、存储了很多<key,value>对的哈希表。通过key,可以存储或查询任意的数据。客户端可以把数据存储在多台memcached上。当查询数据时,客户端首先参考节点列表计算出key的哈希值(阶段一哈 希),进而选中一个节点;客户端将请求发送给选中的节点,然后memcached节点通过一个内部的哈希算法(阶段二哈希),查找真正的数据 (item)。举个列子,假设有3个客户端1, 2, 3,3台memcached A, B, C:Client 1想把数据”barbaz”以key “foo”存储。Client 1首先参考节点列表(A, B, C),计算key “foo”的哈希值,假设memcached B被选中。接着,Client 1直接connect到memcached B,通过key “foo”把数据”barbaz”存储进去。Client 2使用与Client 1相同的客户端库(意味着阶段一的哈希算法相同),也拥有同样的memcached列表(A, B, C)。于是,经过相同的哈希计算(阶段一),Client 2计算出key “foo”在memcached B上,然后它直接请求memcached B,得到数据”barbaz”。各种客户端在memcached中数据的存储形式是不同的(perl Storable, php serialize, java hibernate, JSON等)。一些客户端实现的哈希算法也不一样。但是,memcached服务器端的行为总是一致的。最后,从实现的角度看,memcached是一个非阻塞的、基于事件的服务器程序。这种架构可以很好地解决C10K problem ,并具有极佳的可扩展性。可以参考A Story of Caching ,这篇文章简单解释了客户端与memcached是如何交互的。memcached最大的优势是什么?请仔细阅读上面的问题(即memcached是如何工作的)。Memcached最大的好处就是它带来了极佳的水平可扩展 性,特别是在一个巨大的系统中。由于客户端自己做了一次哈希,那么我们很容易增加大量memcached到集群中。memcached之间没有相互通信, 因此不会增加 memcached的负载;没有多播协议,不会网络通信量爆炸(implode)。memcached的集群很好用。内存不够了?增加几台 memcached吧;CPU不够用了?再增加几台吧;有多余的内存?在增加几台吧,不要浪费了。基于memcached的基本原则,可以相当轻松地构建出不同类型的缓存架构。除了这篇FAQ,在其他地方很容易找到详细资料的。看看下面的几个问题吧,它们在memcached、服务器的local cache和MySQL的query cache之间做了比较。这几个问题会让您有更全面的认识。memcached和MySQL的query cache相比,有什么优缺点?把 memcached引入应用中,还是需要不少工作量的。MySQL有个使用方便的query cache,可以自动地缓存SQL查询的结果,被缓存的SQL查询可以被反复地快速执行。Memcached与之相比,怎么样呢?MySQL的query cache是集中式的,连接到该query cache的MySQL服务器都会受益。* 当您修改表时,MySQL的query cache会立刻被刷新(flush)。存储一个memcached item只需要很少的时间,但是当写操作很频繁时,MySQL的query cache会经常让所有缓存数据都失效。* 在多核CPU上,MySQL的query cache会遇到扩展问题(scalability issues)。在多核CPU上,query cache会增加一个全局锁(global lock), 由于需要刷新更多的缓存数据,速度会变得更慢。* 在MySQL的query cache中,我们是不能存储任意的数据的(只能是SQL查询结果)。而利用memcached,我们可以搭建出各种高效的缓存。比如,可以执行多个独立 的查询,构建出一个用户对象(user object),然后将用户对象缓存到memcached中。而query cache是SQL语句级别的,不可能做到这一点。在小的网站中,query cache会有所帮助,但随着网站规模的增加,query cache的弊将大于利。* query cache能够利用的内存容量受到MySQL服务器空闲内存空间的限制。给数据库服务器增加更多的内存来缓存数据,固然是很好的。但是,有了 memcached,只要您有空闲的内存,都可以用来增加memcached集群的规模,然后您就可以缓存更多的数据。memcached和服务器的local cache(比如PHP的APC、mmap文件等)相比,有什么优缺点?首先,local cache有许多与上面(query cache)相同的问题。local cache能够利用的内存容量受到(单台)服务器空闲内存空间的限制。不过,local cache有一点比memcached和query cache都要好,那就是它不但可以存储任意的数据,而且没有网络存取的延迟。* local cache的数据查询更快。考虑把highly common的数据放在local cache中吧。如果每个页面都需要加载一些数量较少的数据,考虑把它们放在local cached吧。* local cache缺少集体失效(group invalidation)的特性。在memcached集群中,删除或更新一个key会让所有的观察者觉察到。但是在local cache中, 我们只能通知所有的服务器刷新cache(很慢,不具扩展性),或者仅仅依赖缓存超时失效机制。* local cache面临着严重的内存限制,这一点上面已经提到。memcached的cache机制是怎样的?Memcached主要的cache机制是LRU(最近最少用)算法+超时失效。当您存数据到memcached中,可以 指定该数据在缓存中可以呆多久Which is forever, or some time in the future。如果memcached的内存不够用了,过期的slabs会优先被替换,接着就轮到最老的未被使用的slabs。memcached如何实现冗余机制?不实现!我们对这个问题感到很惊讶。Memcached应该是应用的缓存层。它的设计本身就不带有任何冗余机制。如果一个memcached节点失去了所 有数据,您应该可以从数据源(比如数据库)再次获取到数据。您应该特别注意,您的应用应该可以容忍节点的失效。不要写一些糟糕的查询代码,寄希望于 memcached来保证一切!如果您担心节点失效会大大加重数据库的负担,那么您可以采取一些办法。比如您可以增加更多的节点(来减少丢失一个节点的影 响),热备节点(在其他节点down了的时候接管IP),等等。memcached如何处理容错的?不处理!:) 在memcached节点失效的情况下,集群没有必要做任何容错处理。如果发生了节点失效,应对的措施完全取决于用户。节点失效时,下面列出几种方案供您选择:* 忽略它! 在失效节点被恢复或替换之前,还有很多其他节点可以应对节点失效带来的影响。* 把失效的节点从节点列表中移除。做这个操作千万要小心!在默认情况下(余数式哈希算法),客户端添加或移除节点,会导致所有的缓存数据不可用!因为哈希参照的节点列表变化了,大部分key会因为哈希值的改变而被映射到(与原来)不同的节点上。* 启动热备节点,接管失效节点所占用的IP。这样可以防止哈希紊乱(hashing chaos)。* 如果希望添加和移除节点,而不影响原先的哈希结果,可以使用一致性哈希算法(consistent hashing)。您可以百度一下一致性哈希算法。支持一致性哈希的客户端已经很成熟,而且被广泛使用。去尝试一下吧!* 两次哈希(reshing)。当客户端存取数据时,如果发现一个节点down了,就再做一次哈希(哈希算法与前一次不同),重新选择另一个节点(需要注意 的时,客户端并没有把down的节点从节点列表中移除,下次还是有可能先哈希到它)。如果某个节点时好时坏,两次哈希的方法就有风险了,好的节点和坏的节 点上都可能存在脏数据(stale data)。如何将memcached中item批量导入导出?您不应该这样做!Memcached是一个非阻塞的服务器。任何可能导致memcached暂停或瞬时拒绝服务的操作都应该值得深思熟虑。向 memcached中批量导入数据往往不是您真正想要的!想象看,如果缓存数据在导出导入之间发生了变化,您就需要处理脏数据了;如果缓存数据在导出导入 之间过期了,您又怎么处理这些数据呢?因此,批量导出导入数据并不像您想象中的那么有用。不过在一个场景倒是很有用。如果您有大量的从不变化 的数据,并且希望缓存很快热(warm)起来,批量导入缓存数据是很有帮助的。虽然这个场景并不典型,但却经常发生,因此我们会考虑在将来实现批量导出导入的功能。Steven Grimm,一如既往地,,在邮件列表中给出了另一个很好的例子:http://lists.danga.com/pipermail/memcached/2007-July/004802.html 。但是我确实需要把memcached中的item批量导出导入,怎么办??好吧好吧。如果您需要批量导出导入,最可能的原因一般是重新生成缓存数据需要消耗很长的时间,或者数据库坏了让您饱受痛苦。如果一个memcached节点down了让您很痛苦,那么您还会陷入其他很多麻烦。您的系统太脆弱了。您需要做一些优化 工作。比如处理”惊群”问题(比如 memcached节点都失效了,反复的查询让您的数据库不堪重负…这个问题在FAQ的其他提到过),或者优化不好的查询。记住,Memcached 并不是您逃避优化查询的借口。如果您的麻烦仅仅是重新生成缓存数据需要消耗很长时间(15秒到超过5分钟),您可以考虑重新使用数据库。这里给出一些提示:* 使用MogileFS(或者CouchDB等类似的软件)在存储item。把item计算出来并dump到磁盘上。 MogileFS可以很方便地覆写item,并提供快速地访问。.您甚至可以把MogileFS中的item缓存在memcached中,这样可以加快读 取速度。 MogileFS+Memcached的组合可以加快缓存不命中时的响应速度,提高网站的可用性。* 重新使用MySQL。 MySQL的 Inn
Windows下的Memcache安装
很多phper不知道如何在Windows下搭建Memcache的开发调试环境,最近个人也在研究Memcache,记录下自己安装搭建的过程。其实我开始研究Memcache的时候并不知道居然还有memcached for Win32这个鸟东西,害得我在CnetOS下折腾1天才搞定,今天突然发现Windows下的Memcache进行开发调试完全没有问题,所以写篇Memcache的文档分享给大家。Windows下的Memcache安装:1. 下载memcache的windows稳定版,解压放某个盘下面,比如在c:memcached2. 在终端(也即cmd命令界面)下输入 ‘c:memcachedmemcached.exe -d install’ 安装3. 再输入: ‘c:memcachedmemcached.exe -d start’ 启动。NOTE: 以后memcached将作为windows的一个服务每次开机时自动启动。这样服务器端已经安装完毕了。4.下载php_memcache.dll,请自己查找对应的php版本的文件5. 在C:winntphp.ini 加入一行 ‘extension=php_memcache.dll’6.重新启动Apache,然后查看一下phpinfo,如果有memcache,那么就说明安装成功!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 显示帮助Memcache环境测试:运行下面的php文件,如果有输出This is a test!,就表示环境搭建成功。开始领略Memcache的魅力把!< ?php$mem = new Memcache;$mem->connect(”127.0.0.1″, 11211);$mem->set(’key’, ‘This is a test!’, 0, 60);$val = $mem->get(’key’);echo $val;?>     摘自:http://www.ccvita.com/258.html      Memcached在WIN32下的相关设置 memcached  for win32 下载地址:http://code.jellycan.com/memcached/1.在WIN32下 无法使用命令更改内存大小,端口等 ,只能通过修改注册表实现有些命令需要通过服务参数来执行,我们可以用下面方法修改这些服务参数。修改前先停止 memcached 服务。(1) 打开注册表,找到 HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesmemcached Server。(2) 修改 ImagePath 项,比如 ""C:memcachedmemcached.exe" -d runservice -m 100 -p 1234",这样服务启动后监听端口就成了 1234,最大缓存内存就是 100 MB。2.可以通过telnet 查看当前状态telnet 192.168.1.2 11211stats----------------------------------------STAT pid 3932   --进程IDSTAT uptime 137STAT time 1207723245STAT version 1.2.1  --版本号STAT pointer_size 32STAT curr_items 999999  --当前ITEM 激活中的STAT total_items 999999  --总ITEMSTAT bytes 51888843STAT curr_connections 5  --当前连接数STAT total_connections 6 --总连接数STAT connection_structures 6STAT cmd_get 0   --进行GET的次数STAT cmd_set 999999  --进行SET的次数STAT get_hits 0   --命中数STAT get_misses 0  --命中失败数STAT bytes_read 24888902STAT bytes_written 8000378STAT limit_maxbytes 524288000 --分配的总内存空间END 当SET一个已有的ITEM时,total_items 会加1,curr_items 不会改变Memcached采用LRU(Least Recently Used:最近最少被使用)算法,对长时间没有SET的ITEM会作为垃圾处理,在分配的内存空间不足的情况下,当有新的ITEM进来,会踢掉最老的一个ITEM在分配64M空间的情况下,插入50W个ITEM,curr_item  314568total_item 499999就是说64M只能放314568个ITEM,有十多万 item是被当作垃圾踢掉了.当把内存增加到500M时,情况不同了STAT curr_items 999999  STAT total_items 999999  所有的ITEM都在内存里了,命中率肯定就100%了999999 个ITEM占了125M的内存private string[] serverlist = { "192.168.1.2:11211","192.168.1.3:11211" };memcached 会自动分配ITEM到多台机器上,取的时候也会自动从台机器上取,用户不用考虑KEY分配的问题 php 使用memcachedPHP membercached 扩展下载地址:http://downloads.php.net/pierre/1.把php_memcache.dll放到php的安装文件里的扩展文件夹中,也就是放在php的ext目录下2.修改php.ini这个配置文件,加入extension=php_memcache.dll 这一行代码。3.重启apache,然后用php写一个phpinfo()函数就,如果列表里出现了memcache就说明安装成功了。       
PHP_Memcache函数详解
memcache函数所有的方法列表如下:Memcache::add – 添加一个值,如果已经存在,则返回falseMemcache::addServer – 添加一个可供使用的服务器地址Memcache::close – 关闭一个Memcache对象Memcache::connect – 创建一个Memcache对象memcache_debug – 控制调试功能Memcache::decrement – 对保存的某个key中的值进行减法操作Memcache::delete – 删除一个key值Memcache::flush – 清除所有缓存的数据Memcache::get – 获取一个key值Memcache::getExtendedStats – 获取进程池中所有进程的运行系统统计Memcache::getServerStatus – 获取运行服务器的参数Memcache::getStats – 返回服务器的一些运行统计信息Memcache::getVersion – 返回运行的Memcache的版本信息Memcache::increment – 对保存的某个key中的值进行加法操作Memcache::pconnect – 创建一个Memcache的持久连接对象Memcache::replace -对一个已有的key进行覆写操作Memcache::set – 添加一个值,如果已经存在,则覆写Memcache::setCompressThreshold – 对大于某一大小的数据进行压缩Memcache::setServerParams – 在运行时修改服务器的参数Memcache::add用法 bool Memcache::add ( string $key , mixed $var [, int $flag [, int $expire ]] ) 说明:如果$key不存在的时候,使用这个函数来存储$var的值。功能相同的函数是memcache_add()。 参数:$key :将要存储的键值。$var :存储的值,字符型和整型会按原值保存,其他类型自动序列化以后保存。$flag:是否用MEMCACHE_COMPRESSED来压缩存储的值,true表示压缩,false表示不压缩。$expire:存储值的过期时间,如果为0表示不会过期,你可以用unix时间戳或者描述来表示从现在开始的时间,但是你在使用秒数表示的时候,不要超过2592000秒 (表示30天)。 返回值:如果成功则返回 TRUE,失败则返回 FALSE。如果$key值已经存在,则会返回FALSE。 其他情况下Memcache::add()的用法类似于Memcache::set()。例子: <?php$memcache_obj = memcache_connect(”localhost”, 11211);memcache_add($memcache_obj, ’var_key’, ’test variable’, false, 30);$memcache_obj->add(’var_key’, ’test variable’, false, 30);?> Memcache::addServer用法 bool Memcache::addServer ( string $host [, int $port [, bool $persistent [, int $weight [, int$timeout [, int $retry_interval [, bool $status [, callback $failure_callback ]]]]]]] ) 说明:添加一个可供使用的服务器地址到连接池中,连接用Memcache::addServer打开,脚本执行完后自动关闭,或者可以用Memcache::close()手动关闭。相同函数是memcache_add_server()。当用这个方法的时候(相对于Memcache::connect()和 Memcache::pconnect()方法),网络连接只有等需要的时候才会建立,因此不会因为增加很多的服务器到连接池而增加系统负担,因为很多服务器可能没有使用。故障恢复会发生在这个方法执行的任何阶段,只要其他的服务器是正常的,这些连接请求的失败用户不会注意到。任何一种socket或者memcached服务器级的错误可以触发故障恢复。正常的客户端错误比如增加一个存在的键值不会引发故障恢复。 参数:$host服务器的地址$port服务器端口$persistent是否是一个持久连接$weight这台服务器在所有服务器中所占的权重$timeout连接的持续时间$retry_interval连接重试的间隔时间,默认为15,设置为-1表示不进行重试$status控制服务器的在线状态$failure_callback允许设置一个回掉函数来处理错误信息。 返回值:如果成功则返回 TRUE,失败则返回 FALSE。 例子:<?php $memcache = new Memcache;$memcache->addServer(’memcache_host’, 11211);$memcache->addServer(’memcache_host2′, 11211); $memcache_obj = memcache_connect(’memcache_host’, 11211);memcache_add_server($memcache_obj, ’memcache_host2′, 11211);?> Memcache::close用法 bool Memcache::close ( void ) 说明:关闭memcache服务器连接。这个函数不会关闭长连接,长连接只有在web服务器关闭或者重启的时候才会关闭。相同的函数memcache_close()返回值:如果成功则返回 TRUE,失败则返回 FALSE。例子: <?php$memcache_obj = memcache_connect(’memcache_host’, 11211);memcache_close($memcache_obj);$memcache_obj = new Memcache;$memcache_obj->connect(’memcache_host’, 11211);$memcache_obj->close();?> Memcache::connect用法bool Memcache::connect ( string $host [, int $port [, int $timeout ]] ) 说明:打开memcached服务器连接,建立一个到memcached服务器的连接,用Memcache::connect打开的连接会在脚本执行完毕后自动关闭。你也可以用Memcache::close()去关闭连接。相同的函数是memcache_connect()。参数:$host:指向memcached正在收听的链接的主机,这个参数会有另一种特殊的连接方式unix:///path/to/memcached.sock,即用unix的域名sockets,这种情况下,端口必须设置为0$port:指向memcached正在收听的链接的端口,用unix的域名sockets的情况下,端口必须设置为0$timeout:用于连接守护进程的秒数,当你改变默认的1秒的值的时候,你需要考虑一下,如果你的连接太慢的话,你可能会失去缓存的优势。 返回值:如果成功则返回 TRUE,失败则返回 FALSE。例子:<?php$memcache_obj = memcache_connect(’memcache_host’, 11211);$memcache = new Memcache;$memcache->connect(’memcache_host’, 11211);?>memcache::debug bool memcache_debug ( bool $on_off ) 说明:控制调试功能,前提是php在编译的时候使用了-enable-debug选项,否则这个函数不会有作用。参数:$on_off:true表示开启调试,false表示关闭调试返回值:如果php在编译的时候使用了-enable-debug选项,返回true,否则返回falseMemcache::decrement用法int Memcache::decrement ( string $key [, int $value ] ) 说明:Memcache::decremen方法的作用是对保存的某个key中的值进行减法操作,用法跟Memcache::increment类似。你也可以用memcache_decrement()函数。参数:Key:想要减少的键的名字Value:想要减少的值。 返回值:如果成功,返回被减少后的值,如果失败返回false。例子: <?php$memcache = new Memcache;$memcache->connect(’localhost’, 11211);$memcache->set(’test_item’, 8);$memcache->increment(’test_item’, 4);echo $memcache->decrement(’test_item’, 7);// 显示 5?> 这个例子连Memcache::increment函数都一块演示了。Memcache::delete用法bool Memcache::delete ( string $key [, int $timeout ] ) 说明:删除一个key值,如果参数$timeout被设置,那么存储的值会在设置的秒数以后过期,你也可以用函数memcache_delete() 返回值:如果成功则返回 TRUE,失败则返回 FALSE。 例子: <?php$memcache_obj = memcache_connect(’memcache_host’, 11211);memcache_delete($memcache_obj, ’key_to_delete’, 10);$memcache_obj = new Memcache;$memcache_obj->connect(’memcache_host’, 11211);$memcache_obj->delete(’key_to_delete’, 10);?> Memcache::flushbool Memcache::flush ( void ) 说明:清除所有缓存的数据。Memcache::flush实际上没有释放资源,它仅仅将所有的缓存标记为过期,这样可以使新的缓存来覆盖被占的内存空间。一样的函数是memcache_flush() 返回值:如果成功则返回 TRUE,失败则返回 FALSE。 例子: <?php$memcache_obj = memcache_connect(’memcache_host’, 11211);memcache_flush($memcache_obj);$memcache_obj = new Memcache;$memcache_obj->connect(’memcache_host’, 11211);$memcache_obj->flush();?> Memcache::getstring Memcache::get ( string $key [, int &$flags ] )array Memcache::get ( array $keys [, array &$flags ] ) 说明:方法的作用是获取一个key值,key值可以是一个数组,结果会包含键值对。 参数:$key是键值或者一个键的数组值。$flags如果这个参数存在,那么$flags跟写入这个参数的值相关,这些$flags 类似于Memcache::set()函数里的$flags。 返回值:如果成功,则返回key对应的值,如果失败则返回false.
Memcache linux 安装
安装libevent:   下载 http://www.monkey.org/~provos/libevent/   安装:# tar zxvf libevent-1.2.tar.gz         # cd libevent-1.2         # ./configure –prefix=/usr         # make         # make install  测试:      # ls -al /usr/lib | grep libevent        lrwxrwxrwx 1 root root 21 11?? 12 17:38 libevent-1.2.so.1 -> libevent-1.2.so.1.0.3        -rwxr-xr-x 1 root root 263546 11?? 12 17:38 libevent-1.2.so.1.0.3        -rw-r–r– 1 root root 454156 11?? 12 17:38 libevent.a        -rwxr-xr-x 1 root root 811 11?? 12 17:38 libevent.la        lrwxrwxrwx 1 root root 21 11?? 12 17:38 libevent.so -> libevent-1.2.so.1.0.3安装服务器sudo apt-get install memcached$ memcached -d -m 50 -p 11211 -u root参数说明 -m 指定使用多少兆的缓存空间;-p 指定要监听的端口; -u 指定以哪个用户来运行安装php 模块sudo apt-get install php5-memcacheMemcache的参数说明:-d   选项是启动一个守护进程,-m  是分配给Memcache使用的内存数量,单位是MB,默认64MB   -M  return error on memory exhausted (rather than removing items)-u  是运行Memcache的用户,如果当前为root 的话,需要使用此参数指定用户。-l   是监听的服务器IP地址,默认为所有网卡。-p  是设置Memcache的TCP监听的端口,最好是1024以上的端口-c  选项是最大运行的并发连接数,默认是1024-P  是设置保存Memcache的pid文件   -f   <factor>   chunk size growth factor (default: 1.25)   -I   Override the size of each slab page. Adjusts max item size(1.4.2版本新增)  也可以启动多个守护进程,但是端口不能重复
Xcache
Cache 的 INI 配置终于到了解释 xcache.ini 的时候了, 不管你有没有PHP INI 基础知识.载入 XCache 模块;; 安装成 zend extension (推荐), 路径一般是 "$extension_dir/xcache.so" zend_extension = /usr/local/lib/php/extensions/non-debug-non-zts-xxx/xcache.so ;; Windows 系统例子: zend_extension_ts = c:/php/extensions/php_xcache.dll ;; 或者您也可把 XCache 安装成 extension, 注意确保您的 extension_dir 设置正确, 并 把 xcache.so 或者 php_xcache.dll 放到该目录里面 ; extension = xcache.so ;; 或者 Win32 系统: ; extension = php_xcache.dllXCache AdministrationNameDefaultChangeablexcache.admin.user"mOo"PHP_INI_SYSTEMxcache.admin.pass""PHP_INI_SYSTEMxcache.admin.enable_auth"on"PHP_INI_SYSTEMxcache.testOffPHP_INI_SYSTEMxcache.coredump_directory""PHP_INI_SYSTEMxcache.admin.user string验证名.xcache.admin.pass stringmd5 后的验证密码, 亦即 md5(您的密码), 留空则禁用管理页面.xcache.test string仅在测试一些功能的时候才启用. 如果您不知道这个功能的作用, 则您不需要知道.xcache.coredump_directory string设置在 crash (SIGSEGV/SIGABRT) 时保存 core dump 文件的路径. 留空则禁止, 或者设置为类似 "/tmp/phpcore/" 的目录. 确保这个路径可以被 php 写入文件. (与 open_basedir 无关).xcache.admin.enable_auth string如果你打算自己处理验证, 用这个选项禁止 HTTP 验证功能. 值得注意的是任意 vhost 用户都可以安装一个 XCache admin 页面, 如果禁止了内建 HTTP 验证, 则他们亦不需要权限即可访问管理页面. 出于安全考虑, 您应该尽量考虑保留 XCache 内建验证功能, 针对 XCache admin 页面特定地址取消网页服务器的 mod_auth 这个选项仅在 1.2.x 系列有作用, 起始版本 1.2.1XCache CacherNameDefaultChangeablexcache.cacherOnPHP_INI_SYSTEMxcache.sizePHP_INI_ALLxcache.count1PHP_INI_SYSTEMxcache.slots8KPHP_INI_SYSTEMxcache.ttlPHP_INI_SYSTEMxcache.gc_intervalPHP_INI_SYSTEMxcache.var_sizePHP_INI_SYSTEMxcache.var_count1PHP_INI_SYSTEMxcache.var_slots8KPHP_INI_SYSTEMxcache.var_ttlPHP_INI_ALLxcache.var_maxttlPHP_INI_SYSTEMxcache.var_gc_interval300PHP_INI_SYSTEMxcache.readonly_protectionOffPHP_INI_SYSTEMxcache.mmap_path"/dev/zero"PHP_INI_SYSTEMxcache.cacher boolean使用/不使用 opcode 缓存器. xcache.size = 0 时无效.xcache.size int0 禁止, 非 0 则启用缓存器. 请注意您系统所允许的 mmap 最大值.xcache.count int指定将 cache 切分成多少块. 参考 SplittedCachexcache.slots size只是作为 hash 槽个数的参考值, 您可以放心地缓冲超过这个个数的项目.xcache.ttl seconds设置缓冲项目的 Ttl (Time To Live) 值, 0=永不过期.xcache.gc_interval seconds检查过期项目, 回收内存空间的间隔.xcache.var_size intxcache.var_count intxcache.var_slots sizexcache.var_gc_interval seconds同上, 不过用于数据缓冲而不是 opcode 缓冲.xcache.var_ttl secondsxcache_(get|set|inc|dec) 等的默认 ttl 值.xcache.var_maxttl seconds最大 ttl 值, 程序无法指定超过这个最大值的 ttl.xcache.readonly_protection boolean如果启用了 ReadonlyProtection, 将会略微降低性能, 但是会提高一定的安全系数. 这个选项对于 xcache.mmap_path = /dev/zero 无效.xcache.mmap_path string对于 *nix, xcache.mmap_path 是 文件路径, 不是目录. 对于 Win32, xcache.mmap_path 只是匿名的 map 名, 不是实际的文件路径. 如果您要启用 ReadonlyProtection 请用类似 "/tmp/xcache" 的路径. 2 组 php 不该共用同一个路径 (/dev/zero 除外).XCache OptimizerNameDefaultChangeablexcache.optimizerOffPHP_INI_ALLxcache.optimizer boolean启用优化器 (目前无效).XCache CoveragerNameDefaultChangeablexcache.coveragerOffPHP_INI_ALLxcache.coveragedump_directory"/tmp/pcov/"PHP_INI_SYSTEMxcache.coverager booleanEnable coverage data collecting for xcache.coveragedump_directory and xcache_coverager_start/stop/get/clean() functions (will hurt executing performance)xcache.coveragedump_directory stringDirectory to dump coverage data. Make sure it's readable (care open_basedir) by coverage viewer script. Requires xcache.coverager=On(2)安装$ wget http://xcache.lighttpd.net/pub/Releases/1.2.2/xcache-1.2.2.tar.gz$ tar -zxvf xcache-1.2.2.tar.gz$ cd xcache-1.2.2$ phpize$ ./configure --enable-xcache --with-php-config=/usr/local/bin/php-config$ make$ make test$ make install