PHP 8.5.0 Alpha 2 available for testing

Memcache::connect

memcache_connect

(PECL memcache >= 0.2.0)

Memcache::connect -- memcache_connectEstablece una conexión con el servidor Memcache

Descripción

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

Memcache::connect() establece una conexión con el servidor de caché Memcache. La conexión, que ha sido abierta utilizando la función Memcache::connect() se cerrará automáticamente al final del script. No obstante, puede cerrarse manualmente utilizando la función Memcache::close().

Parámetros

host

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

port

Especifica el puerto donde memcache escucha para conexiones. Defina este parámetro a 0 al utilizar sockets Unix.

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

timeout

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

Valores devueltos

Esta función retorna true en caso de éxito o false si ocurre un error.

Ejemplos

Ejemplo #1 Ejemplo con Memcache::connect()

<?php

/* API procedimental */

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

/* API orientada a objetos */

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

?>

Notas

Advertencia

Cuando el parámetro port no es especificado, 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 la aplicación, esto puede conducir 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 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
11 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