CakeFest 2024: The Official CakePHP Conference

Memcache::addServer

(PECL memcache >= 2.0.0)

Memcache::addServerДобавляет сервер memcached в пул соединений

Описание

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() добавляет сервер в пул соединений. Вы также можете использовать функцию memcache_add_server().

При использовании этого метода (в отличие от Memcache::connect() и Memcache::pconnect()) сетевое соединение не будет установлено, пока в нем не возникнет необходимость. В связи с этим можно не опасаться снижения производительности при добавлении большого количества серверов в пул, так как, возможно, они никогда не будут использованы.

Потребность в обеспечении отказоустойчивости может возникнуть на любом этапе в любом методе и если при этом будут доступен хотя бы один сервер из пула - пользователь не получит какого-либо оповещения. Любой тип ошибки сокета или сервера Memcached (за исключением ошибки переполнения памяти) может включить протокол обеспечения отказоустойчивости. Обычные клиентские ошибки, такие как добавление существующего ключа, не вызовут подобного поведения.

Замечание:

Эта функция была добавлена в Memcache версии 2.0.0.

Список параметров

host

Указывает на хост с запущенным сервисом memcached. Этот параметр можно задать в виде unix:///path/to/memcached.sock для использования сокетов Unix, но в таком случае будет необходимо установить параметр port, равным 0.

port

Указывает порт, по которому доступен сервис memcached. Необходимо установить равным 0 если используются сокеты Unix.

Пожалуйста обратите внимание: port по умолчанию равен memcache.default_port. Поэтому рекомендуется всегда указывать номер порта при использовании этого метода.

persistent

Использовать ли постоянное соединение. По умолчанию true.

weight

Необходимое количество созданных пакетов данных для этого сервера, что, в свою очередь, определяет вероятность его выбора. Вероятность рассчитывается относительно общего веса всех серверов.

timeout

Время ожидания в секундах для установления соединения с сервером. Дважды подумайте прежде чем устанавливать это значение больше чем 1. Это может нивелировать всю пользу от использования memcached.

retry_interval

Управляет частотой проверки доступности отказавшего сервера, по умолчанию 15 секунд. Если задать значение "-1", то попыток проверить доступность сервера предприниматься не будет. Ни этот параметр, ни параметр persistent не оказывают никакого влияния, если модуль загружен динамически через функцию dl().

Каждая провалившаяся структура соединения имеет собственное значение времени ожидания и, пока оно не превышено, структура будет пропущена, после чего попробует выбрать другой сервер для обслуживания запроса. После того как время соединения истекло, оно либо удачно пересоединится, либо будет помечено провалившимся и будет ждать ещё retry_interval секунд. Обычно эффект заключается в том, что каждый процесс веб-сервера будет ожидать retry_interval секунд при обслуживании запроса.

status

Определяет, должен ли сервер помечен флагом как "онлайн". Установка этого параметра в false и retry_interval в -1 позволит сохранить сервер в пуле, но не использовать его в алгоритме распределения ключей. Запрос к этому серверу либо запустит механизм обеспечения отказоустойчивости, либо сразу же прервётся с ошибкой, в зависимости от настройки memcache.allow_failover. По умолчанию равно true, что означает, что сервер активен и готов принимать запросы.

failure_callback

Позволяет пользователю задать функцию обратного вызова, которая запустится в случае какой-либо ошибки. Эта функция будет вызвана раньше, чем будет запущен механизм обеспечения отказоустойчивости. Функция принимает два параметра - имя хоста и порт отказавшего сервера.

timeoutms

Возвращаемые значения

Возвращает true в случае успешного выполнения или false, если возникла ошибка.

Примеры

Пример #1 Пример использования Memcache::addServer()

<?php

/* объектно-ориентированное API */

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

/* процедурное API */

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

?>

Примечания

Внимание

Когда значение port не указано, этот метод использует значение, указанное в ini-директиве PHP memcache.default_port. Если это значение было изменено где-нибудь ещё в вашем приложении, то это может дать непредсказуемые результаты. По этой причине лучше всегда явно указывать порт при вызове метода.

Смотрите также

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