The Memcache client library is responsible for picking the right server to set/get data. That's why addServer is what you want to use rather than connect, when you have more than one Memcache server. A subsequent set/get will then connect on demand to the appropriate instance as needs be. Disconnection to whatever servers were connected to happening when you close or your script terminates.
Memcache instances added to your Memcache object via addServer should be added in the same order in your application to ensure that the same server is picked for use with the same key.
A client library may be implemented to run a CRC on the key and do a modulus over the number of instances in the list to select an instance from the list for the set/get. This ensures that data is spread nicely across the nodes.
That all works nicely behind the scenes for you in your PHP code, as long as you add your list of Memcache instances in a consistent manner with addServer.
(PECL memcache >= 2.0.0)
Memcache::addServer — Add a memcached server to connection pool
$port= 11211 [, bool
Memcache::addServer() adds a server to the connection pool. The connection, which was opened using Memcache::addServer() will be automatically closed at the end of script execution, you can also close it manually with Memcache::close(). You can also use the memcache_add_server() function.
When using this method (as opposed to Memcache::connect() and Memcache::pconnect()) the network connection is not established until actually needed. Thus there is no overhead in adding a large number of servers to the pool, even though they might not all be used.
Failover may occur at any stage in any of the methods, as long as other servers are available the request the user won't notice. Any kind of socket or Memcached server level errors (except out-of-memory) may trigger the failover. Normal client errors such as adding an existing key will not trigger a failover.
This function has been added to Memcache version 2.0.0.
Point to the host where memcached is listening for connections. This parameter may also specify other transports like unix:///path/to/memcached.sock to use UNIX domain sockets, in this case
portmust also be set to 0.
Point to the port where memcached is listening for connections. Set this parameter to 0 when using UNIX domain sockets.
portdefaults to memcache.default_port if not specified. For this reason it is wise to specify the port explicitly in this method call.
Controls the use of a persistent connection. Default to
Number of buckets to create for this server which in turn control its probability of it being selected. The probability is relative to the total weight of all servers.
Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow.
Controls how often a failed server will be retried, the default value is 15 seconds. Setting this parameter to -1 disables automatic retry. Neither this nor the
persistentparameter has any effect when the extension is loaded dynamically via dl().
Each failed connection struct has its own timeout and before it has expired the struct will be skipped when selecting backends to serve a request. Once expired the connection will be successfully reconnected or marked as failed for another
retry_intervalseconds. The typical effect is that each web server child will retry the connection about every
retry_intervalseconds when serving a page.
Controls if the server should be flagged as online. Setting this parameter to
retry_intervalto -1 allows a failed server to be kept in the pool so as not to affect the key distribution algorithm. Requests for this server will then failover or fail immediately depending on the
memcache.allow_failoversetting. Default to
TRUE, meaning the server should be considered online.
Allows the user to specify a callback function to run upon encountering an error. The callback is run before failover is attempted. The function takes two parameters, the hostname and port of the failed server.
port is unspecified, this method defaults to the
value set of the PHP ini directive
If this value was changed elsewhere in your application it might lead to
unexpected results: for this reason it is wise to always specify the port
explicitly in this method call.
TRUE on success or
FALSE on failure.
Example #1 Memcache::addServer() example
/* OO API */
$memcache = new Memcache;
/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_add_server($memcache_obj, 'memcache_host2', 11211);
- Memcache::connect() - Open memcached server connection
- Memcache::pconnect() - Open memcached server persistent connection
- Memcache::close() - Close memcached server connection
- Memcache::setServerParams() - Changes server parameters and status at runtime
- Memcache::getServerStatus() - Returns server status
The $timeoutms argument can be used to specify the timeout in milliseconds, but isn't available in all versions. For example, it exists in php_memcache 2.2.6, but not in 3.0.4. In 2.2.6, if you specify it, then it overrides $timeout.
Caveat emptor: If $timeoutms is not specified, it defaults to the value of memcache.default_timeout_ms in php.ini, which defaults to 1000 if not set. This also overrides $timeout, which has the curious effect that $timeout is always ignored in php_memcache 2.2.6 (either in favor of $timeoutms, memcache.default_timeout_ms or the value 1000, in that order of priority).
Actually if you have two memcached servers from which one of them is on localhost, and the other is on a remote machine you can communicate with both even if you specify the loopback address for the local one.
$memcache_obj = memcache_connect("127.0.0.1", 11211);
This WILL communicate with both hosts but however there are two aspects that must be taken into account:
1. the communication will be done through different network interfaces with the two hosts. It will use the loopback interface for the "127.0.0.1" host (lo in my case on Linux) and the external interface for the "memcache_remote_host" (eth0 in my case). Only if you want to use the same network interface to communicate with both hosts you must use the external IPs of both machines (and all communication will go out through the eth0 interface).
2. the connection with the two hosts will be established differently because of how memcache_connect() and memcache_add_server() work. Therefore the memcache_connect() will initiate the connection to localhost through the loopback interface when it is called, while memcache_add_server() will just add the second server to the pool, but it will not send any package through the network until it's absolutely needed (for example when a memcache_set() command is issued).
The weight of the server must be greater than 0.
If there is no memcached server to use, and you try to set/add variables, the apache will be crashed, with the error message "[notice] child pid 18725 exit signal Segmentation fault (11)" in error_log file.
There are three additional undocumented arguments to the failure callback function. The total list of failure callback arguments is:
- tcp port
- udp port
- error number
- error message
We tried to file this as a bug against the documentation, but the bug report was closed because no patch was included. Please consider this note the "patch" against documentation, because we already wasted too much time on this, and it's better that people know than that people don't know.
If you are stuck with version 1.0.x (as shipped in Ubuntu 10.04 LTS for instance), this is a simple way of providing failover support from a single main server to a single failover server:
$m = new Memcached();
// Immediately check server connection
$m->get('onlinecheck_' . uniqid());
if (in_array($m->getResultCode(), array(Memcached::RES_ERRNO, Memcached::RES_UNKNOWN_READ_FAILURE)))
// Main server not available - Failing over
$m = new Memcached();
The "version" mentioned for this function is the PECL module. To see the PECL version do phpinfo() and look at Memcache section. To see memcached (server) version: Memcache::getVersion(). You can also telnet into memcached server (eg: localhost:11211) and type 'stats' and hit enter.
An important thing to note about this is that if you have 2 memcache servers and one of those servers is your localhost that you will want to specify the external IP addresses of both of those.
$m = memcache_connect('127.0.0.1', 11211);
This will NEVER talk to 10.5.50.20.
So what you need to do is to specify the external IP address of all your servers:
$m = memcache_connect('10.5.50.10', 11211);
For some reason when the PHP memcache module does a connection to localhost it assumes that this is the ONLY memcache server and does not attempt to use others.