<?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)
Esempio n. 2
0
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 * Description of incr
 *
 * @author changdi
 */
//require __DIR__.'/shared.php';
require '../shared.php';
$predis = new Predis\Client($single_server);
var_dump($predis->get('key'));
var_dump($predis->incr('key'));
//var_dump($predis->incr('key',15));
var_dump($predis->decr('key'));
Esempio n. 3
0
    // Check entry value.
    echo ">>> Value for 'k1': " . $redis->get('k1') . "\n";
    // Change entry's value.
    if ($redis->set('k1', 'new_value')) {
        echo ">>> Successfully put entry in cache. \n";
    }
    // Check entry value.
    echo ">>> Value for 'k1': " . $redis->get('k1') . "\n";
    // Put entry to cache.
    if ($redis->set('k2', '2')) {
        echo ">>> Successfully put entry in cache. \n";
    }
    // Check entry value.
    echo ">>> Value for 'k2': " . $redis->get('k2') . "\n";
    // Get two entries.
    $val = $redis->mget('k1', 'k2');
    echo ">>> Value for 'k1' and 'k2': " . var_dump($val) . "\n";
    // Delete on entry.
    if ($redis->del('k1')) {
        echo ">>> Successfully deleted 'k1'. \n";
    }
    // Db size.
    echo ">>> Db size: " . $redis->dbsize() . "\n";
    // Increment.
    echo ">>> Incremented: " . $redis->incr("inc_k") . "\n";
    // Increment by 5.
    echo ">>> Incremented: " . $redis->incrby("inc_k", 5) . "\n";
} catch (Exception $e) {
    echo ">>> Couldn't connected to Redis.";
    echo $e->getMessage();
}
Esempio n. 4
0
			'port' => 6379
		));
	}
	catch (Exception $e) {
		//die($e->getMessage());
	}

	if(isset($url[1]) && $url[1] == 'visits') {
		$i_visits = $redis->get("visits");
		echo json_encode(array('total_visits' => $i_visits));die();
	} elseif($url[1] == 'reset.php') {
		if(isset($url[2]) && $url[2] > 0) $redis->set("visits", $url[2]);
		else $redis->set("visits", 0);
	}

	$redis->incr("visits");
	$i_visits = $redis->get("visits");

	// get zone
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "http://metadata.google.internal/computeMetadata/v1/instance/zone");
	curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		'Metadata-Flavor: Google'
	));
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$output = curl_exec($ch);
	curl_close($ch);

	if(isset($output) && !(empty($output))) {
		$a_zone = explode('/', $output);
		$zone = end($a_zone);
Esempio n. 5
0
<?php 
# N.B. : Predis is rediculously slow, but it's easier than installing binaries for the presentation:
#       http://alekseykorzun.com/post/53283070010/benchmarking-memcached-and-redis-clients
require 'predis/lib/Predis/Autoloader.php';
Predis\Autoloader::register();
$redis = new Predis\Client();
// 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');
Esempio n. 6
0
 public function get_ohlc($pair, $start, $end, $bid_offer, $timeslice, $lag = 0)
 {
     //to seconds factor lookup
     $this->to_seconds_factor['s'] = 1;
     $this->to_seconds_factor['m'] = 60;
     $this->to_seconds_factor['h'] = 60 * 60;
     $this->to_seconds_factor['d'] = 60 * 60 * 24;
     //predis class
     require 'Predis/lib/Predis/Autoloader.php';
     Predis\Autoloader::register();
     // set some utility variables
     $range = $end - $start;
     $startTime = gmstrftime('%Y-%m-%d %H:%M:%S', $start / 1000);
     $endTime = gmstrftime('%Y-%m-%d %H:%M:%S', $end / 1000);
     //set suggested timeslice depending on range
     //[1s,5s,10s,20s,30s,1m,5m,10m,20m,30m,1h,2h,3h,6h,1d,1w,1M]
     if (!isset($timeslice)) {
         $stick_threshold = 300;
         //on screen count threshold
         //seconds
         if ($range < $stick_threshold * 1000) {
             $timeslice = '1s';
         } elseif ($range < $stick_threshold * 5 * 1000) {
             $timeslice = '5s';
         } elseif ($range < $stick_threshold * 10 * 1000) {
             $timeslice = '10s';
         } elseif ($range < $stick_threshold * 20 * 1000) {
             $timeslice = '20s';
         } elseif ($range < $stick_threshold * 30 * 1000) {
             $timeslice = '30s';
             //minutes
         } elseif ($range < $stick_threshold * 60 * 1000) {
             $timeslice = '1m';
         } elseif ($range < $stick_threshold * 60 * 5 * 1000) {
             $timeslice = '5m';
         } elseif ($range < $stick_threshold * 60 * 10 * 1000) {
             $timeslice = '10m';
         } elseif ($range < $stick_threshold * 60 * 20 * 1000) {
             $timeslice = '20m';
         } elseif ($range < $stick_threshold * 60 * 30 * 1000) {
             $timeslice = '30m';
             //hour
         } elseif ($range < $stick_threshold * 60 * 60 * 1000) {
             $timeslice = '1h';
         } elseif ($range < $stick_threshold * 60 * 60 * 2 * 1000) {
             $timeslice = '2h';
         } elseif ($range < $stick_threshold * 60 * 60 * 3 * 1000) {
             $timeslice = '3h';
         } elseif ($range < $stick_threshold * 60 * 60 * 6 * 1000) {
             $timeslice = '6h';
             //day
         } elseif ($range < $stick_threshold * 60 * 60 * 24 * 1000) {
             $timeslice = '1d';
             //week
         } elseif ($range < $stick_threshold * 60 * 60 * 7 * 1000) {
             $timeslice = '1w';
             //month
         } else {
             $timeslice = '1M';
         }
     }
     //validate and parse timeslice
     if (!preg_match('/^(?P<dur>\\d+)(?P<len>s|m|h|d|w|M)$/', $timeslice, $matches)) {
         die("Invalid timeslice parameter: {$timeslice}");
     }
     //timeslice duration (1,2,3,4,..)
     $ts_duration = $matches['dur'];
     //timeslice length (s,m,h,d,w,M)
     $ts_len = $matches['len'];
     //check durations modulus of parent
     //60 seconds in a minute and 60 minute in an hour
     if (in_array($ts_len, array('s', 'm'))) {
         if (60 % $ts_duration != 0) {
             //not evenly divisable by 60
             die("Invalid 1timeslice parameter: {$ts_duration}{$ts_len}");
         }
     }
     //24 hours in day
     if (in_array($ts_len, array('h'))) {
         if (24 % $ts_duration != 0) {
             //not evenly divisable by 24
             die("Invalid timeslice parameter: {$ts_duration}{$ts_len}");
         }
     }
     //max 2 day|week|month
     if (in_array($ts_len, array('d', 'w', 'M'))) {
         if ($ts_duration > 2) {
             //not valid duration
             die("Invalid timeslice parameter: {$ts_duration}{$ts_len}");
         }
     }
     //check are not cacheing week and month
     $is_caching = in_array($ts_len, array('w', 'M')) ? false : true;
     //add lag
     if ($lag > 0) {
         if (!in_array($ts_len, array('w', 'M'))) {
             //to sec
             $sec = $this->to_seconds_factor[$ts_len] * $ts_duration;
             //lag start
             $start = (ceil($start / 1000 / $sec) * $sec - $sec * $lag) * 1000;
         } else {
             if ($ts_len == 'w') {
                 $date = date_create_from_format('U', $start);
                 date_sub($date, date_interval_create_from_date_string("{$lag} weeks"));
             }
             if ($ts_len == 'M') {
                 $date = date_create_from_format('U', $start);
                 date_sub($date, date_interval_create_from_date_string("{$lag} months"));
             }
             //save new start
             $start = date_format($date, 'U') * 1000;
         }
     }
     //if no week or Month, round start/end time to match candle length
     if (!in_array($ts_len, array('w', 'M'))) {
         //to sec
         $sec = $this->to_seconds_factor[$ts_len] * $ts_duration;
         //round up start time, round down end time
         $startTime = date('Y-m-d H:i:s', ceil($start / 1000 / $sec) * $sec);
         //round down end time
         $endTime = date('Y-m-d H:i:s', floor($end / 1000 / $sec) * $sec + $sec - 1);
     }
     //init vars
     $time_slices = array();
     $result = array();
     $ranges = array();
     $cache = array();
     $time_slices = array();
     $empty_time_slices = array();
     $is_cache_miss = false;
     $redis = new Predis\Client();
     $redis_zset = "{$pair}:{$bid_offer}:{$timeslice}";
     //query redis cache
     if ($is_caching) {
         //get list of expected time slices
         $time_slices = $this->buildTimeSlices($ts_len, $ts_duration, $start / 1000, $end / 1000);
         //check redis cache
         $return = $redis->zrangebyscore($redis_zset, $start / 1000, $end / 1000, array('withscores' => true));
         //build cache datastructure
         foreach ($return as $row) {
             $cache[$row[1]] = $row[0];
         }
         //get empty timeslices
         $return = $redis->zrangebyscore('empty:' . $redis_zset, $start / 1000, $end / 1000, array('withscores' => true));
         //remove empty timeslices from time_slices
         foreach ($return as $row) {
             unset($time_slices[$row[1]]);
         }
         //find missing slices
         $cache_miss_slices = array_diff_key($time_slices, $cache);
         //check for cache misses
         if (count($cache_miss_slices) > 0) {
             $is_cache_miss = true;
             $redis->incr('cache_misses');
             //get ranges for missing slices
             $ranges = $this->buildRangeFromMissingTimeSlices($ts_len, $ts_duration, $cache_miss_slices);
         } else {
             $redis->incr('cache_hits');
             $results = $cache;
         }
     } else {
         //build full range
         $ranges[] = array('startTime' => $startTime, 'endTime' => $endTime);
     }
     //hit database if we are not caching or if we have a cache miss
     if (!$is_caching || $is_cache_miss) {
         //db
         $return = $this->fetchMySQLAndCache($ts_len, $ts_duration, $is_cache_miss ? $cache_miss_slices : $time_slices, $ranges, $is_caching, $redis, $redis_zset, $pair, $bid_offer);
         //add missing slices to cache obj
         if ($is_cache_miss) {
             foreach ($return as $row) {
                 extract($row);
                 $cache[$datetime] = "[{$datetime},{$open},{$high},{$low},{$close},{$vol}]";
             }
             //sort by key (timestamp)
             ksort($cache);
             $results = $cache;
         } else {
             //build non cached results results
             foreach ($return as $row) {
                 extract($row);
                 $results[] = "[{$datetime},{$open},{$high},{$low},{$close},{$vol}]";
             }
         }
     }
     return $results;
 }
 /**
  *Saves the value in redis-server using Predis class object
  *
  */
 private function saveUsingPredis()
 {
     require __DIR__ . "/../vendor/predis/predis/autoload.php";
     \Predis\Autoloader::register();
     $redis = new \Predis\Client();
     if ($redis->get('counter') == NULL) {
         $redis->set('counter', 0);
     } else {
         $redis->incr('counter');
     }
     $redis->set($redis->get('counter'), $this->value);
 }
Esempio n. 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'];
 }
Esempio n. 9
0
<?php

include_once '../../common.php';
include_once S_ROOT . './source/function_space.php';
include_once 'verify.php';
$uid = $_SGLOBAL['supe_uid'];
$result = array();
$query = $_SGLOBAL['db']->query("select avatar,name,username from " . tname('space') . " where uid='{$uid}' LIMIT 1");
if ($rs = $_SGLOBAL['db']->fetch_array($query)) {
    require 'Predis/Autoloader.php';
    Predis\Autoloader::register();
    $client = new Predis\Client();
    $keyT = 'ihome_T' . $uid;
    $client->incr($keyT);
    if (empty($rs['name'])) {
        $rs['name'] = $rs['username'];
    }
    $name = $rs['name'];
    if ($rs['avatar']) {
        $face = avatar($uid, 'big', TRUE);
    } else {
        $query = $_SGLOBAL['db']->query("SELECT sex FROM " . tname('spacefield') . " WHERE uid='{$uid}' LIMIT 1");
        if ($gd = $_SGLOBAL['db']->result($query)) {
            if ($gd == 1) {
                $gender = 'm';
            } else {
                $gender = 'f';
            }
        } else {
            $gender = "m";
        }