PHP module Memcached has more functions than Memcache

  • 2020-05-07 19:24:56
  • OfStack

For example, PECL has two modules of Memcached, Memcache and Memcached. Currently, most PHP environments use Memcache version without d in its name. This version was released earlier and is a native version.

installs Memcached version of PHP module

wget http://download.tangent.org/libmemcached-0.35.tar.gz
tar zxf libmemcached-0.35.tar.gz
cd libmemcached-0.35
./configure
make
make install

wget http://pecl.php.net/get/memcached-1.0.0.tgz
tar zxf memcached-1.0.0.tgz
cd memcached-1.0.0
phpize
./configure
make
make install

Open php.ini add:

extension = "memcached.so"

This completes the installation and you can confirm it by following the command:

php -m | grep mem

demonstrates the new functionality in the Memcached version

Let's first make up a problem and assume that the initial value of counter is an integer. Instead of using increment method, get/set is used to increment by 1 every time.

In the Memcache version, we can only do this in the following general way:

$m = new Memcache();
$m- > addServer('localhost', 11211);
$v = $m- > get('counter');
$m- > set('counter', $v + 1);

Since the get/set actions cannot be operated on as one atom, there is a possibility of loss when multiple processes are working at the same time, and even more annoying, you never know when the loss is occurring.

Here's how we did it in Memcached:

$md = new Memcached();
$md- > addServer('localhost', 11211);
$v = $md- > get('counter', null, $token)
$md- > cas($token, 'counter', $v + 1);

cas Memcached version provides function, namely a optimistic locking function, if you put the value of $token var_dump come out, you will find the $token is actually a version number, if $token version number is obtained by get when cas don't correspond, means that there have been other updated operation, cas operation will fail at this time, as for how to continue to operate, see you.

Note: if you want to manually reproduce the conflict in 1, sleep for a few seconds between get and cas, and then make two copies of the script.

By the way, the recommended hash Settings for the Memcached version of the module are as follows:

$md- > setOption(Memcached::OPT_DISTRIBUTION, Memcached::DISTRIBUTION_CONSISTENT);
$md- > setOption(Memcached::OPT_HASH, Memcached::HASH_CRC);

summary

The Memcached version has many features that Memcache doesn't have, such as automatic support for multiple servers via getByKey, setByKey, etc.

added: http: / / code google. com p/memcached/wiki/PHPClientComparison

Related articles: