CakeFest 2024: The Official CakePHP Conference

Memcache::addServer

(PECL memcache >= 2.0.0)

Memcache::addServerAñadir servidor memcache al grupo de conexiones

Descripción

Memcache::addServer(
    string $host,
    int $port = 11211,
    bool $persistent = ?,
    int $weight = ?,
    int $timeout = ?,
    int $retry_interval = ?,
    bool $status = ?,
    callable $failure_callback = ?,
    int $timeoutms = ?
): bool

Memcache::addServer() añade un servidor al grupo de conexiones. También se puede usar la función memcache_add_server().

Cuando se usa este método (opuestamente a Memcache::connect() y Memcache::pconnect()) la conexión no se establece hasta que es necesaria. De esta forma no hay sobrecarga al añadir un gran número de servidores en el grupo de conexiones, aunque no todos van a ser utilizados.

La conexión puede caer en cualquier momento usando cualquiera de los métodos, mientras otros servidores estén disponibles para hacer la petición el usuario no notará nada. Cualquier tipo de errores de socket o servidor Memcached (excepto out-of-memory) seguramente harán caer la conexión. Errores en el cliente como añadir una llave que ya existe no provocará la caida de la conexión.

Nota:

Esta función fué añadida en Memcache versión 2.0.0.

Parámetros

host

Apunta al host donde memcached está esperando conexiones. Este parámetro también se puede especificar con otros transportes como unix:///path/to/memcached.sock para usar domain UNIX sockets, en este caso port debe también establecerse a 0.

port

Apunta al puerto donde memcache está esperando para conexiones. Establece este parámetro a 0 cuando se usan UNIX domain sockets.

Por favor note: port será por defecto memcache.default_port en caso de no especificarse. Por esta razón, se recomienda especificar el puerto explícitamente en la llamada a este método.

persistent

Controla el uso de una conexión persistente. Por defecto true.

weight

Número de segmentos para crear de este servidor, que a su vez controlan la probabilidad de que sea seleccionado. La probabilidad es relativa a la de peso total de todos los servidores.

timeout

Valor en segundos que se utilizará para conectar con el demonio. Piense dos veces antes de cambiar el valor predeterminado de 1 segundo - se puede perder todas las ventajas de la caché si su conexión es demasiado lenta.

retry_interval

Controla la frecuencia de reintentos cuando falla la conexión, el valor por defecto es 15 segundos. Si establece este parámetro a -1 desactivará el reintento automático. Ni esta opción ni el parámetro persistent tienen ningún efecto cuando la extensión se carga dinámicamente a través de dl().

Cada conexión struct fallida tiene su propio timeout y antes de que caduque, el struct será omitido cuando se selecionen backends para servir una petición.Cuando caduque la conexión se reconectará satisfactoriamente o se marcará como fallida por otros retry_interval segundos. El típico efecto es que cada servidor web hijo reintentará la conexión cada retry_interval cuando se sirven páginas.

status

Controla si el servidor debe ser marcado como online. Estableciendo este parámetro a false y retry_interval a -1 permite a un servidor que falle a ser mantenido en el grupo para no afectar el algoritmo de distribución de llaves. Las peticiones a este servidor fallarán inmediatamente dependiendo en la opción memcache.allow_failover. Por defecto to true, que significa que el servidor se considera online.

failure_callback

Permite al usuario a especificar la llamada a una función de retorno a ejectuar cuando se encuentre un error. La llamada de retorno se ejecuta antes de que se produzca la caída en la conexión. La función toma dos parámetros, el hostname y el puerto del puerto que ha fallado.

timeoutms

Notas

Advertencia

Cuando no se especifica port, este método usará el valor establecido en la directiva ini memcache.default_port de PHP. Si este valor se cambiara en cualquier lugar de la aplicación podría conducir a resultados inesperados; por esta razón, es prudente especificar el puerto explícitamente en la llamada a este método.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo Memcache::addServer()

<?php

/* OO API */

$memcache = new Memcache;
$memcache->addServer('memcache_host', 11211);
$memcache->addServer('memcache_host2', 11211);

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_add_server($memcache_obj, 'memcache_host2', 11211);

?>

Ver también

add a note

User Contributed Notes 6 notes

up
6
rstaveley at seseit dot com
12 years ago
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.
up
3
enno dot rehling at gmail dot com
12 years ago
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).
up
2
joewynn dot nz+phpnet at gmail dot com
10 years ago
Note that this method will always return TRUE because a connection is not actually made at call time. See this bug report for more information: https://bugs.php.net/bug.php?id=58193
up
1
eu at serbannistor dot ro
12 years ago
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.

<?php
$memcache_obj
= memcache_connect("127.0.0.1", 11211);
memcache_add_server($memcache_obj, "memcache_remote_host");
$memcache_obj->set('var_key', time());
?>

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).
up
0
iwind dot liu at gmail dot com
14 years ago
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.
up
-5
Jean-Baptiste Quenot
15 years ago
The default value for the "weight" argument is 1
To Top