Existen varios clientes para trabajar con Redis desde PHP: (Fuente: http://redis.io/clients )
- Predis
- Phpredis
- Rediska
- RedisServer
- Credis
- Redisent
Para este ejemplo vamos a utilizar Predis. Lo primero que tenemos que hacer es clonar predis desde github:
$ git clone git://github.com/nrk/predis.git
Luego, creamos un archivo "test-predis.php" con este contenido para probar conexión, seteo de datos alfanuméricos, listas, update de valores y expiración.
<?php
require "predis/autoload.php";
Predis\Autoloader::register();
try {
$redis = new Predis\Client();
echo "Successfully connected to Redis";
echo "<hr>";
$redis->set("hello_world", "Hi from php!");
$value = $redis->get("hello_world");
var_dump($value);
echo ($redis->exists("Santa Claus")) ? "true" : "false";
echo "<hr>";
$redis->set("I 2 love Php!", "Also Redis now!");
$value = $redis->get("I 2 love Php!");
$redis->set("I 2 love Php!", "Also Redis now!");
$value = $redis->get("I 2 love Php!");
echo "<hr>";
$redis->hset("taxi_car", "brand", "Toyota");
$redis->hset("taxi_car", "model", "Yaris");
$redis->hset("taxi_car", "license number", "RO-01-PHP");
$redis->hset("taxi_car", "year of fabrication", 2010);
$redis->hset("taxi_car", "nr_starts", 0);
echo "License number: " .
$redis->hget("taxi_car", "license number") . "<br>";
// remove license number
$redis->hdel("taxi_car", "license number");
// increment number of starts
$redis->hincrby("taxi_car", "nr_starts", 1);
$taxi_car = $redis->hgetall("taxi_car");
echo "All info about taxi car";
echo "<pre>";
var_dump($taxi_car);
echo "</pre>";
uso de uso de
echo "<hr>";
$list = "PHP Frameworks List";
$redis->rpush($list, "Symfony 2");
$redis->rpush($list, "Symfony 1.4");
$redis->lpush($list, "Zend Framework");
echo "Number of frameworks in list: " . $redis->llen($list) . "<br>";
$arList = $redis->lrange($list, 0, -1);
echo "<pre>";
print_r($arList);
echo "</pre>";
// the last entry in the list
echo $redis->rpop($list) . "<br>";
// the first entry in the list
echo $redis->lpop($list) . "<br>";
echo "<hr>";
// set the expiration for next week
$redis->set("expire in 1 week", "I have data for a week");
$redis->expireat("expire in 1 week", strtotime("+1 week"));
$ttl = $redis->ttl("expire in 1 week"); // will be 604800 seconds
// set the expiration for one hour
$redis->set("expire in 1 hour", "I have data for an hour");
$redis->expire("expire in 1 hour", 3600);
$ttl = $redis->ttl("expire in 1 hour"); // will be 3600 seconds
// never expires
$redis->set("never expire", "I want to leave forever!");
}
catch (Exception $e) {
echo "Couldn't connected to Redis";
echo $e->getMessage();
}
Es importante que en /etc/redis.conf estén configurados estos valores:
maxmemory 2048000
maxmemory-policy allkeys-lru
El primero es para fijar la memoria para caché en 2 mb y el segundo para la expiración de las keys.
No hay comentarios:
Publicar un comentario