downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Memcache::close> <Memcache::add
Last updated: Fri, 20 May 2011

view this page in

Memcache::addServer

(PECL memcache >= 2.0.0)

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

Descripción

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

Memcache::addServer() añade un servidor al grupo de conexiones. La conexión, la cual se abrió mediante Memcache::addServer() se cerrará automaticamente cuando finalice la ejecución del script, también se puede cerrar manualmente usando Memcache::close(). También se puede utilizar 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.

Note:

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.

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

Valores devueltos

Devuelve TRUE en caso de éxito o FALSE en caso de error.

Ejemplos

Example #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



Memcache::close> <Memcache::add
Last updated: Fri, 20 May 2011
 
add a note add a note User Contributed Notes Memcache::addServer
eu at serbannistor dot ro 04-May-2011 01:30
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).
anthony at iclasspro dot com 01-Dec-2010 11:40
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.

<?php
$m
= memcache_connect('127.0.0.1', 11211);
memcache_add_server($m, '10.5.50.20');
?>
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:
<?php
$m
= memcache_connect('10.5.50.10', 11211);
memcache_add_server($m, '10.5.50.20');
?>

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.
iwind dot liu at gmail dot com 08-Feb-2010 08:14
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.
rich at drivecurrent dot com 22-Aug-2008 10:12
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.
Jean-Baptiste Quenot 05-May-2008 08:08
The default value for the "weight" argument is 1

 
show source | credits | stats | sitemap | contact | advertising | mirror sites