Memcache::connect

memcache_connect

(PECL memcache >= 0.2.0)

Memcache::connect -- memcache_connectAbre a conexão do servidor memcached

Descrição

Memcache::connect(string $host, int $port = ?, int $timeout = ?): bool
memcache_connect(string $host, int $port = ?, int $timeout = ?): Memcache

Memcache::connect() estabelece uma conexão com o servidor memcached. A conexão, que foi aberta usando Memcache::connect() será fechada automaticamente no fim da execução do script. Pode-se também fechá-la com Memcache::close().

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 sockets 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.

timeout

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

Valor Retornado

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

Exemplos

Exemplo #1 Exemplo de Memcache::connect()

<?php

/* API procedural */

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

/* API orientada a objeto */

$memcache = new Memcache;
$memcache->connect('memcache_host', 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 no seu aplicativo, 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) 2 notes

up
10
geoffrey dot hoffman at gmail dot com
14 years ago
If memcached is working, calling memcache_connect( ) returns an Object instance, not a boolean. If memcached is not working, calling memcache_connect( ) throws a notice AND a warning (and returns false as expected).

<?php
/* memcache is running */
$test1 = memcache_connect('127.0.0.1',11211);
echo
gettype($test1);
// object
echo get_class($test1);
// Memcache

/* memcached is stopped */
$test2 = memcache_connect('127.0.0.1',11211);

/*
Notice: memcache_connect(): Server 127.0.0.1 (tcp 11211) failed with: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
(10060) in C:\Program Files\Support Tools\- on line 1

Warning: memcache_connect(): Can't connect to 127.0.0.1:11211, A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
(10060) in C:\Program Files\Support Tools\- on line 1
*/

echo gettype($test2);
// boolean
echo $test2===false;
// 1
?>

There appears to be no way to check whether memcached is actually running without resorting to error suppression:

<?php
$test3
= @memcache_connect('127.0.0.1',11211);
if(
$test3===false ){
// memcached is _probably_ not running
}
?>
up
-4
webysther at gmail dot com
10 years ago
In describing the timeout there is a statement that is not completely correct, increase the timeout does not necessarily preclude or unfeasible memcache, only allows the system to wait for more concurrent connections, which is a large minority of the number of connections, this causes several problems and could simply be corrected if the timeout was increased and perform some tests.
To prove the concept and show that the connection does not wait if the server goes down:

<?PHP

while ( ++$loop < 10000 ) {
try {
$memcache = new Memcache;
@
$memcache->pconnect( "127.0.0.1" , 11211 , 30 );
$loopset = 0;
$loopget = 0;

while ( ++
$loopset < 50 ) {
if ( @
$memcache->set( "foo" , "bar" ) === false ) {
echo
"Fail!" . PHP_EOL;
}
}

while ( ++
$loopget < 500 ) {
if ( @
$memcache->get( "foo" ) === false ) {
echo
"Fail!" . PHP_EOL;
}
}

if (
$loop % 100 == 0 ) {
echo
"Try: " . $loop . PHP_EOL;
}
} catch (
Exception $e ) {
echo
"Fail: " . $e->getMessage() . PHP_EOL;
}
}

?>

Replace with an invalid host and test the timeout will not make a difference! It serves only for connections to the socket that are occupied.

More detail about troubleshooting timeouts in memcached google code.
To Top