Пример #1
7
<?php

require 'vendor/autoload.php';
Predis\Autoloader::register();
$client = new Predis\Client(array('host' => '127.0.0.1', 'port' => 6379), array('prefix' => 'php:'));
$client->set("string:my_key", "Hello World");
$client->get("string:my_key");
# "Hello World"
$client->incr("string:counter");
$client->mget(array("string:my_key", "string:counter"));
# array('Hello World', '2')
$client->rpush("list:my_list", "item1", "item2");
$client->lpop("list:my_list");
# 'item1'
$client->hset("set:redis_book", "title", "Redis Essentials");
$client->hgetall("set:redis_book");
# array('title' => 'Redis Essentials')
$client->sadd("set:users", "alice", "bob");
$client->smembers("set:users");
# array('bob', 'alice')
$client->zadd("sorted_set:programmers", 1940, "Alan Kay");
$client->zadd("sorted_set:programmers", 1912, "Alan Turing");
$client->zrange("sorted_set:programmers", 0, -1, "withscores");
# array('Alan Turing' => 1912, 'Alan Kay' => 1940)
Пример #2
0
	$client = new Predis\Client([
	    'scheme' => 'tcp',
	    'host'   => '127.0.0.1',
	    'port'   => 6379,
	]);

*/
// Simplest demo how to use Redis
/*
$redis->set("hello_world", "Hi from php!");
$value = $redis->get("hello_world");
echo $value;
*/
// 123 - id of property
$redis->hmset("123", array("type" => "нерухомість поза містом", "name" => "Приватний будинок поза містом", "location" => "с. Ульянівка", "description" => "Приватний будинок поза містом. Приватизована земельна ділянка. Світло, вода, газ - присутні. Є місце для будівництва.", "sdelka" => "Продаж", "rooms" => 5, "floors" => 2, "area" => 90, "price" => "12000\$"));
$res = $redis->hgetall('123');
//echo var_dump($res);
?>
  <div class="container" style="margin-top: 15%;">
  <div class="comments-list">
	<div class="media">
	  <p class="price pull-right"><span class="label label-primary"><?php 
echo $res['sdelka'];
?>
</span></p>
	  <a class="media-left" href="#">
	    <img class="ob-img" src="../img/no-image.png">
	  </a>
	  <div class="media-body" style="padding-top: 5px;">

	    <h4 class="media-heading user_name"><a href="belova1.html" target="_blank"><?php 
Пример #3
0
// Really simple way to set a key/value pair
$redis->set('foo', 'bar');
$value = $redis->get('foo');
echo $value . "\n";
// There's no UPDATE commands where we're going! Just set it again.
$redis->set('foo', 'baz');
$value = $redis->get('foo');
echo $value . "\n";
// Here we go incrementing unset values. No need to run messy UPSERT stuff.
echo "You've run this script " . $redis->incr('counter') . " times btw.\n";
// Tom is a simple associative array
$tom = array('name' => 'Thomas Hunter', 'age' => 27, 'height' => 165);
// The predis library makes setting hashes easy
$redis->hmset('tom', $tom);
// Now lets load that hash
$tom = $redis->hgetall('tom');
// As you can see, the object is exactly the same
var_dump($tom);
echo "\n";
// We can get a single field from our hash if we want
$tomsage = $redis->hget('tom', 'age');
echo "Tom is {$tomsage} years old.\n";
// We can increment a single field from the hash as well
$redis->hincrby('tom', 'age', '10');
$tom = $redis->hgetall('tom');
var_dump($tom);
echo "\n";
// Here's another simple associative array
$jessica = array('name' => 'Jessica Rabbit', 'age' => 30, 'height' => 140);
// Lets convert it into a JSON string
$jessica_json = json_encode($jessica);
// Operations such as LRANGE, ZRANGE and others can potentially generate replies
// containing a huge number of items. In some corner cases, such replies might
// end up exhausting the maximum allowed memory allocated for a PHP process.
// Multibulk iterators can be handy because they allow you to stream multibulk
// replies using plain old PHP iterators, making it possible to iterate them with
// a classic `foreach` loop and avoiding to consume an excessive amount of memory.
//
// PS: please note that multibulk iterators are supported only by the standard
// connection backend class (Predis\Connection\StreamConnection) and not the
// phpiredis-based one (Predis\Connection\PhpiredisConnection).
// Create a client and force the connection to use iterable multibulk responses.
$client = new Predis\Client($single_server + array('iterable_multibulk' => true));
// Prepare an hash with some fields and their respective values.
$client->hmset('metavars', array('foo' => 'bar', 'hoge' => 'piyo', 'lol' => 'wut'));
// By default multibulk iterators iterate over the reply as a list of items...
foreach ($client->hgetall('metavars') as $index => $item) {
    echo "[{$index}] {$item}\n";
}
/* OUTPUT:
[0] foo
[1] bar
[2] hoge
[3] piyo
[4] lol
[5] wut
*/
// ... but certain multibulk replies are better represented as lists of tuples.
foreach ($client->hgetall('metavars')->asTuple() as $index => $kv) {
    list($key, $value) = $kv;
    echo "[{$index}] {$key} => {$value}\n";
}
Пример #5
0
//
// NOTE: This request allows anonymous access, but if user authentication is required then the
// identity of the request should be verified (often times with session cookies) before a valid
// response is given.
$app->delete('/help/queue', function () use($app, $redis, $opentok, $config) {
    // Dequeue the next help session
    $redisResponse = $redis->lpop(HELP_QUEUE_KEY);
    if (!handleRedisError($redisResponse, $app, 'Não foi possível atender a uma sessão de vídeo chat da fila.')) {
        return;
    }
    $helpSessionKey = $redisResponse;
    if (empty($helpSessionKey)) {
        // The queue was empty
        $app->response->setStatus(204);
    } else {
        $redisResponse = $redis->hgetall($helpSessionKey);
        if (!handleRedisError($redisResponse, $app, 'Não foi possível ler a sessão de vídeo chat.')) {
            return;
        }
        $helpSessionData = $redisResponse;
        $responseData = array('apiKey' => $config->opentok('key'), 'sessionId' => $helpSessionData['sessionId'], 'token' => $opentok->generateToken($helpSessionData['sessionId']), 'customerName' => $helpSessionData['customerName'], 'problemText' => $helpSessionData['problemText']);
        // Once the help session is dequeued, we also clean it out of the storage.
        // If keeping the history of this help session is important, we could mark it as dequeued
        // instead. If we had authentication for the representative, then we could also mark the
        // help session with the identity of the representative.
        $redisResponse = $redis->del($helpSessionKey);
        if (!handleRedisError($redisResponse, $app, 'Não foi possível remover a sessão após a retirada da fila.')) {
            return;
        }
        $app->response->headers->set('Content-Type', 'application/json');
        $app->response->setBody(json_encode($responseData));
Пример #6
0
    print $e->getMessage();
    print "\n";
}
if ($stage == "two") {
    $listofkeys = $redis->keys('*');
    $inclvals = filter_input(INPUT_POST, 'inclvals');
    if ($inclvals == "false") {
        header('MIME-Version: 1.0');
        header("Content-Type: application/json");
        $tmp = json_encode($listofkeys);
        $jout = str_replace('\\/', '/', $tmp);
        print $jout;
    } else {
        for ($i = 0; $i != count($listofkeys); $i++) {
            $listofvals[$i]->key = $listofkeys[$i];
            $listofvals[$i]->vals = $redis->hgetall($listofkeys[$i]);
            // print "<p>$i</p>";
        }
        $tmp = json_encode($listofvals);
        $jout = str_replace('\\/', '/', $tmp);
        print $jout;
    }
    exit(0);
}
// stage zero or one, both have this
$urival = filter_input(INPUT_POST, 'URI');
// update/add a record
if ($stage == "zero") {
    // read other stuff from HTTP POST form data
    $hint1 = filter_input(INPUT_POST, 'hint1');
    $hint2 = filter_input(INPUT_POST, 'hint2');
Пример #7
0
<?php

header('Content-Type: text/html; charset=utf-8', true);
error_reporting(E_ALL);
require "predis/autoload.php";
Predis\Autoloader::register();
$redis = new Predis\Client();
/*  If uses external server

	$client = new Predis\Client([
	    'scheme' => 'tcp',
	    'host'   => '127.0.0.1',
	    'port'   => 6379,
	]);

*/
//29392
// id объекта недвижимости. Он есть ключом для всего хэша. По запросу именно id будут выдаваться все данные объекта из базы.
$prop_id = rand(00, 99999);
echo 'GENERATED PROPERTY ID: ', $prop_id, '<br>';
// создаем хэш (объект недвижимости) с генерированным id в качестве ключа.
$redis->hmset($prop_id, array("type" => "Новобудови", "name" => "Двокімнатна квартира", "location" => "м.Чернігів, просп. Миру", "description" => "Продається двокімнатна квартира в центрі Чернігова", "sdelka" => "Продаж", "rooms" => 2, "floor" => 5, "floors_total" => 9, "area" => 32, "price" => "22000\$"));
// и запишем этот ключ в отдельную базу, где будем хранить все id всех объявлений.
$list = 'Properties';
$redis->rpush($list, $prop_id);
echo '<br>Properties in list: ', $redis->llen($list), '<br><br>';
echo '<br>There are: <pre>', print_r($redis->lrange($list, 0, -1)), '</pre><br><br>';
//echo '<br>', var_dump($res), '<br><br>';
$res1 = $redis->hgetall($prop_id);
echo var_dump($res1);
Пример #8
0
 public static function metricsVerb()
 {
     # grab the arguments. this function has variable arguments.
     # the first argument is assumed to be the metrics "verb" being requested.
     # the remaining argument are assumed to be the arguments to the "verb".
     require "Predis/Autoloader.php";
     Predis\Autoloader::register();
     if (func_num_args() == 0) {
         return -599;
         # incorrect number of arguements
     } else {
         $params = func_get_args();
     }
     $verbName = $params[0];
     # ...and hookup with redis
     try {
         $redis = new Predis\Client(array("host" => "127.0.0.1", "port" => 6379, "database" => 8));
     } catch (Exception $e) {
         die($e->getMessage());
     }
     # pull in verb information, checking that verb is available and correct in the process
     $verb = $redis->hgetall($verbName);
     if (!$verb) {
         return -500;
     }
     # verb not found
     # pull in the remaining arguments
     if (func_num_args() != $verb['args']) {
         return -599;
         # incorrect number of arguments
     }
     # compose the query
     $query = "{$verbName}_";
     for ($i = 1; $i < count($params); $i++) {
         $query = $query . "{$params[$i]}";
     }
     # Validation test - parameters
     $verbDate = new Datetime("{$params[1]}-{$params[2]}-01");
     # Grab the list of databases needed by this verb and calculate the minimum date range
     # over which a calculation can be performed.
     $minDate = new Datetime("1970-1-1");
     $maxDate = new Datetime("3000-1-1");
     foreach (explode(',', $verb['databases']) as $db) {
         $dbInfo = $redis->hgetall($db);
         $dbMin = new Datetime($dbInfo['minDate']);
         $dbMax = new Datetime($dbInfo['maxDate']);
         if ($dbMin > $minDate) {
             $minDate = $dbMin;
         }
         if ($dbMax < $maxDate) {
             $maxDate = $dbMax;
         }
     }
     if ($verbDate < $minDate or $verbDate > $maxDate) {
         return -501;
     }
     # parameter out of range
     # Validation test - is there an answer for this query in the cache?
     # if not, kick off a backend job to calculate one.
     $result = $redis->hgetall($query);
     if (!$result) {
         call_user_func_array("celerySubmit", $params);
         return -401;
         # result unavailable, calculating result now, come back later
     }
     # Validation test - software version
     # If the result's software version number does not match the verb's version number, re-compute
     if ($result['software'] != $verb['version']) {
         call_user_func_array("celerySubmit", $params);
         return -402;
         # result out of date, calculating updated result now, come back later
     }
     # Validation test - database version
     # if any of the results' database version number(s) do not match the database(s)'s version number(s), re-compute
     foreach (explode(',', $verb['databases']) as $db) {
         $dbInfo = $redis->hgetall($db);
         if ($dbInfo['version'] != $result[$db]) {
             call_user_func_array("celerySubmit", $params);
             return -402;
             # result out of date, calculating updated result now, come back later
         }
     }
     # It's all good. Increment the popularity counter and return the cached value.
     $redis->incr('pop_${query}');
     return $result['value'];
 }
Пример #9
0
<?php

require './vendor/predis/predis/src/Autoloader.php';
Predis\Autoloader::register();
#$client = new Predis\Client([
#	'schema' => 'tcp',
#	'host' => 'localhost',
#	'port' => 6379
#]);
$client = new Predis\Client('tcp://localhost:6379');
$results = $client->hgetall('keystone:dynatron/metric::ebis-wlri-analysis:info');
header('Content-Type: application/json');
echo json_encode($results);
#echo "hi";