Memcache::addServer

(PECL memcache >= 2.0.0)

Memcache::addServerAdiciona um servidor memcached ao pool de conexão

Descrição

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() adiciona um servidor ao pool de conexão. Pode-se também usar a função memcache_add_server().

Ao usar este método (ao contrário de Memcache::connect() e Memcache::pconnect()) a conexão de rede não é estabelecida até que seja realmente necessária. Portanto, não há sobrecarga na adição de um grande número de servidores ao pool, mesmo que eles não sejam todos usados.

O failover pode ocorrer em qualquer estágio em qualquer um dos métodos, desde que outros servidores estejam disponíveis, a solicitação não será notada pelo usuário. Qualquer tipo de erro de nível de soquete ou servidor Memcached (exceto falta de memória) pode disparar o failover. Erros normais do cliente, como adicionar uma chave existente, não dispararão um failover.

Nota:

Esta função foi adicionada ao Memcache versão 2.0.0.

Parâmetros

host

Aponta para o host onde o memcached está escutando conexões. Este parâmetro também pode especificar outros transportes como unix:///path/to/memcached.sock para usar soquetes de domínio UNIX, neste caso port também deve ser definido como 0.

port

Aponta para a porta onde o memcached está escutando conexões. Defina este parâmetro como 0 ao usar soquetes de domínio UNIX.

Observe: port assume como padrão memcache.default_port se não for especificado. Por esse motivo, é sensato especificar a porta explicitamente nessa chamada de método.

persistent

Controla o uso de uma conexão persistente. Padrão é true.

weight

Número de buckets a serem criados para este servidor que, por sua vez, controlam sua probabilidade de ser selecionado. A probabilidade é relativa ao peso total de todos os servidores.

timeout

Valor em segundos que será usado para conectar ao daemon. Pense duas vezes antes de alterar o valor padrão de 1 segundo - podem ser perdidas todas as vantagens do cache se a conexão for muito lenta.

retry_interval

Controla a frequência com que um servidor com falha será tentado novamente, o valor padrão é 15 segundos. Definir este parâmetro como -1 desabilita a repetição automática. Nem este nem o parâmetro persistent têm qualquer efeito quando a extensão é carregada dinamicamente via dl().

Cada estrutura de conexão com falha tem seu próprio tempo limite e antes que ela expire a estrutura será ignorada ao selecionar backends para atender a uma solicitação. Uma vez expirada, a conexão será reconectada com sucesso ou marcada como falhada por mais retry_interval segundos. O efeito típico é que cada filho do servidor web tentará novamente a conexão a cada retry_interval segundos ao atender uma página.

status

Controla se o servidor deve ser sinalizado como online. Definir este parâmetro como false e retry_interval como -1 permite que um servidor com falha seja mantido no pool para não afetar o algoritmo de distribuição de chaves. As solicitações para este servidor então farão failover ou falharão imediatamente dependendo da configuração memcache.allow_failover. Padrão é true, significando que o servidor deve ser considerado online.

failure_callback

Permite que o usuário especifique uma função de retorno para ser executada ao encontrar um erro. A função de retorno é executada antes da tentativa de failover. A função leva dois parâmetros, o nome do host e a porta do servidor com falha.

timeoutms

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Exemplos

Exemplo #1 Exemplo de Memcache::addServer()

<?php

/* API orientada a objeto */

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

/* API procedural */

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

?>

Notas

Aviso

Quando o port não é especificado, este método assume como padrão o conjunto de valores da diretiva INI memcache.default_port do PHP. Se este valor foi alterado em outro lugar na aplicação, isso pode levar a resultados inesperados: por este motivo, é sensato sempre especificar a porta explicitamente nesta chamada de método.

Veja Também

adicione uma nota

Notas Enviadas por Usuários (em inglês) 6 notes

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