谈及php搭配memcached使用,已经是老生常谈的问题。但是有一些细节,不见得人人清楚。比如说php的模块memcache和memcached有什么区别等。下面我就简单介绍一下。
1. 目前大多数php环境里使用的都是不带d的memcache版本,这个版本出的比较早,是一个原生版本,完全在php框架内开发的。与之对应的带d的memcached是建立在libmemcached的基础上,所以相对来说,memcached版本的功能更全一些。
memcache:http://cn2.php.net/manual/en/book.memcache.php
memcached:http://cn2.php.net/manual/en/book.memcached.php
2. Memcache是原生实现的,支持OO和非OO两套接口并存。而memcached是使用libmemcached,只支持OO接口。
3. memcached还有个非常称赞的地方,就是flag不是在操作的时候设置了,而是有了一个统一的setOption()。Memcached实现了更多的memcached协议。
4. memcached支持Binary Protocol,而memcache不支持。这意味着memcached会有更高的性能。不过memcached目前还不支持长连接。
下面有一张表,来对比php客户端扩展memcache与memcached
PHP Client Comparison
There are primarily two clients used with PHP. One is the older, more widespread pecl/memcache and the other is the newer, less used, more feature rich pecl/memcached.
Both support the basics such as multiple servers, setting vaules, getting values, increment, decrement and getting stats.
Here are some more advanced features and information.
pecl/memcache | pecl/memcached | |
---|---|---|
First Release Date | 2004-06-08 | 2009-01-29 (beta) |
Actively Developed? | Yes | Yes |
External Dependency | None | libmemcached |
Features | ||
Automatic Key Fixup1 | Yes | No |
Append/Prepend | No | Yes |
Automatic Serialzation2 | Yes | Yes |
Binary Protocol | No | Optional |
CAS | No | Yes |
Compression | Yes | Yes |
Communication Timeout | Connect Only | Various Options |
Consistent Hashing | Yes | Yes |
Delayed Get | No | Yes |
Multi-Get | Yes | Yes |
Session Support | Yes | Yes |
Set/Get to a specific server | No | Yes |
Stores Numerics | Converted to Strings | Yes |
- pecl/memcache will convert an invalid key into a valid key for you. pecl/memcached will return false when trying to set/get a key that is not valid.
- You do not have to serialize your objects or arrays before sending them to the set commands. Both clients will do this for you.
另外一点也是大家比较关心的,就是所使用的算法。大家都知道“一致性hash算法”是当添加或删除存储节点时,对存储在memcached上的数据影响较小的一种算法。那么在php的两个扩展库中,都可以使用该算法,只是设置方法有所不同。
Memcache
修改php.ini添加:
[Memcache]
Memcache.allow_failover = 1
……
……
Memcache.hash_strategy =consistent
Memcache.hash_function =crc32
……
……
或在php中使用ini_set方法:
Ini_set(‘memcache.hash_strategy’,’standard’);
Ini_set(‘memcache.hash_function’,’crc32’);
Memcached
$mem = new memcached();
$mem->setOption(Memcached::OPT_DISTRIBUTION,Memcached::DISTRIBUTION_CONSISTENT);
$mem->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE,true);
http://hi.baidu.com/dong_love_yan/blog/item/afbe1e12d22e7512203f2e21.html