Using multiple memcached instances with options in combination with persistent connections might be confusing:
<?php
$a = new Memcached('memcached_pool');
$a->setOption(Memcached::OPT_COMPRESSION, false);
$b = new Memcached('memcached_pool');
$b->setOption(Memcached::OPT_COMPRESSION, true);
$a->add('key', 'some data');
?>
You might think that connection $a will store everything uncompressed, but this is not the case.
The persistent connection options are changed by the second object creation.
Memcached::__construct
(PECL memcached >= 0.1.0)
Memcached::__construct — Create a Memcached instance
Description
Memcached::__construct
([ string $persistent_id
] )
Creates a Memcached instance representing the connection to the memcache servers.
Parameters
- persistent_id
-
By default the Memcached instances are destroyed at the end of the request. To create an instance that persists between requests, use persistent_id to specify a unique ID for the instance. All instances created with the same persistent_id will share the same connection.
Return Values
A Memcached object.
Examples
Example #1 Creating a Memcached object
<?php
/* Create a regular instance */
$m1 = new Memcached();
echo get_class($m);
/* Create a persistent instance */
$m2 = new Memcached('story_pool');
$m3 = new Memcached('story_pool');
/* now $m2 and $m3 share the same connection */
?>
Memcached::__construct
jeroen at 4worx dot com
16-Nov-2009 10:51
16-Nov-2009 10:51
tschundler at gmail dot com
15-Sep-2009 09:43
15-Sep-2009 09:43
When using persistent connections, it is important to not re-add servers.
This is what you do not want to do:
<?php
$mc = new Memcached('mc');
$mc->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
$mc->addServers(array(
array('mc1.example.com',11211),
array('mc2.example.com',11211),
));
?>
Every time the page is loaded those servers will be appended to the list resulting in many simultaneous open connections to the same server. The addServer/addServers functions to not check for existing references to the specified servers.
A better approach is something like:
<?php
$mc = new Memcached('mc');
$mc->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
if (!count($mc->getServerList())) {
$mc->addServers(array(
array('mc1.example.com',11211),
array('mc2.example.com',11211),
));
}
?>
