PHP 8.5.0 Alpha 1 available for testing

Memcache::addServer

memcache_add_server

(PECL memcache >= 2.0.0)

Memcache::addServer -- memcache_add_serverAñade un servidor memcache a la lista de conexión

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_add_server(
    Memcache $memcache,
    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 a la lista de conexión.

Al utilizar este método (a diferencia de los métodos Memcache::connect() y Memcache::pconnect()), la conexión a la red no se establece hasta que sea necesaria. Además, no hay inconveniente en añadir muchos servidores a la lista, incluso si no todos serán utilizados.

El fallo puede producirse en cualquier momento con cualquier método siempre que otros servidores estén disponibles, la petición no emitirá error. Cualquier interfaz de conexión o nivel de errores de servidor Memcache (a excepción de la falta de memoria) puede lanzar el fallo. Errores normales de cliente como añadir una clave existente no lanzará un fallo.

Nota:

Esta función fue añadida en la versión 2.0.0 de Memcache.

Parámetros

host

Apunta al host donde memcache escucha para conexiones. Este parámetro puede especificar también otros transportes como unix:///path/to/memcached.sock para usar sockets Unix, y en este caso, port debe definirse también a 0.

port

Apunta al puerto donde memcache escucha para conexiones. Defínase este parámetro a 0 al usar sockets Unix.

Nota: Por omisión, el parámetro port toma el valor de la opción de configuración memcache.default_port cuando no se especifica. Por esta razón, es recomendable especificar explícitamente el puerto al llamar a este método.

persistent

Controla el uso de una conexión persistente. El valor por omisión es true.

weight

Número de entradas a crear para este servidor que a su vez controla su probabilidad de ser elegido. La probabilidad es relativa al peso total de todos los servidores.

timeout

Valor en segundos que será utilizado para conectarse al demonio. Piénsese dos veces antes de cambiar el valor por omisión de un segundo - podría perderse todos los beneficios de usar la caché si la conexión es demasiado lenta.

retry_interval

Controla cuántas veces se intentará un servidor que falla, el valor por omisión es de 15 segundos. Si este parámetro vale -1, no se realizará ningún nuevo intento. Ni este parámetro, ni el parámetro persistent tienen efecto cuando esta extensión se carga dinámicamente mediante la función dl().

Cada estructura de conexión fallida tiene su propio tiempo límite y antes de que este expire, será saltada durante la selección del proceso para servir una petición. Una vez expirado, la conexión será correctamente reconectada o marcada como fallida por otro intervalo de retry_interval segundos. El efecto típico es que cada hijo de servidor web intentará la conexión cada retry_interval segundos al servir una página.

status

Controla si el servidor debe ser indicado como en línea. Cuando este parámetro vale false y el parámetro retry_interval vale -1, permite mantener un servidor fallido en la lista y no afectará al algoritmo de distribución de claves. Las peticiones para este servidor fallarán inmediatamente según la configuración del parámetro memcache.allow_failover. Por omisión, este parámetro vale true, significando que el servidor debe ser considerado como en línea.

failure_callback

Permite al usuario especificar una función de retorno para manejar un error. La función de retorno se ejecuta antes de alcanzar el límite de intentos. La función toma dos parámetros; el nombre del host y el puerto del servidor que falló.

timeoutms

Valores devueltos

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

Ejemplos

Ejemplo #1 Ejemplo con Memcache::addServer()

<?php

/* API orientada a objetos */

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

/* API procedimental */

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

?>

Notas

Advertencia

Cuando el parámetro port no se especifica, este método tomará el valor de la directiva de configuración INI memcache.default_port. Si este valor ha sido modificado en otro lugar de su aplicación, esto puede llevar a resultados inesperados: por esta razón, es recomendable siempre especificar el puerto explícitamente al llamar al método.

Ver también

add a note

User Contributed Notes 6 notes

up
6
rstaveley at seseit dot com
14 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
13 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
11 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
14 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
15 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
17 years ago
The default value for the "weight" argument is 1
To Top