/**
  * Display a listing of the resource.
  *
  * @return \Illuminate\Http\Response
  */
 public function index()
 {
     if (\Auth::check() == false) {
         return redirect('/auth/login');
     }
     // 一页多少文章
     $pageNum = 8;
     $userInfo = \Auth::user();
     $data = array();
     $data['articles'] = \App\Article::latest()->get();
     $data['userInfo'] = $userInfo;
     $dataArticles = array();
     $cacheKey = 'laravel:articles:index';
     $redis = new \Predis\Client(array('host' => '127.0.0.1', 'port' => 6379));
     $dataArticles = $redis->get($cacheKey);
     if (!$dataArticles || true) {
         //$dataArticles = \App\Article::latest()->take($pageNum)->with('content')->get()->toArray();
         $dataArticles = \App\Article::latest()->with('content')->paginate($pageNum)->toArray();
         //             var_dump($dataArticles);exit();
         $redis->setex($cacheKey, 3600 * 12, serialize($dataArticles));
     } else {
         $dataArticles = unserialize($dataArticles);
     }
     $data['articles'] = $dataArticles;
     //var_dump($data);exit();
     // $articleArr[0]['relations']['content']['content']
     return view('articles.admin.articleList')->with('data', $data);
 }
示例#2
0
 /**
  * Get an object from the cache
  * @param $key string
  * @return object The result
  */
 public function get($key)
 {
     if (!$this->isEnabled()) {
         return null;
     }
     if (!$this->attemptedConnection) {
         $this->connect();
     }
     $result = $this->handle->get($key);
     return $result != null ? gzdecode($result) : null;
 }
示例#3
0
function getDataJson()
{
    if (isset($_GET['sfrom'])) {
        $jordanGUID = $_GET['jordanGUID'];
        $domain = $_GET['domain'];
        $protocol = $_GET['protocol'];
        $path = $_GET['path'];
        $location = $protocol . $domain . $path;
        $sfrom = $_GET['sfrom'];
        initConnection($db_config);
        //redis 使用
        require '../Predis/Autoloader.php';
        Predis\Autoloader::register();
        $redis = new Predis\Client(array('database' => '0', 'host' => '49.4.129.122', 'port' => 6379));
        $datestr = date("Y_m_d_H");
        $tableName = "request_" . $datestr;
        if ($redis->get("tableName") != $tableName) {
            create_request($tableName);
            $redis->set("tableName", $tableName);
        }
        $request_datetime = date('Y-m-d H:i:s', time());
        writeLog('../logs/' . $tableName . '.log', "{$jordanGUID}\t{$domain}\t{$location}\t{$request_datetime}\n", "a");
        insert_request_entry($jordanGUID, $domain, $location, $sfrom, $request_datetime, $tableName);
        insert_request_entry($jordanGUID, $domain, $location, $sfrom, $request_datetime, "request");
        //echo "success";
    } else {
        //echo "failure";
    }
}
示例#4
0
function getUrlInfo($url)
{
    $client = new \Predis\Client();
    $u = $client->get($url);
    if ($u == null) {
        $info = (object) [];
        $page = file_get_contents('https:' . $url);
        $xml = simplexml_load_string($page);
        $nodes = $xml->xpath("//ul/li[contains(@class, 'interlanguage-link')]/a");
        foreach ($nodes as $node) {
            $info->{$node['lang']} = (string) $node['href'];
        }
        /*
        	Sometimes pages have not a self-reference in interlanguage links,
        	here we enforce it to keep consistency
        */
        preg_match('/^\\/\\/(?<locale>[a-z\\-]*)\\.wikipedia\\.org\\/wiki\\/.*$/', $url, $matches);
        if (isset($matches['locale'])) {
            $info->{$matches['locale']} = $url;
        }
        $enc_info = json_encode($info);
        foreach ($info as $lang => $url) {
            $client->set($url, $enc_info);
        }
        return $info;
    } else {
        return json_decode($u);
    }
}
function get_endpoints_from_redis_for_blog($blog_id)
{
    $key = 'site_id:' . $blog_id . ':webhooks';
    $redis = new Predis\Client(['scheme' => 'tcp', 'host' => REDIS_HOST, 'port' => REDIS_PORT, 'password' => REDIS_PASSWORD]);
    $endpoints = json_decode($redis->get($key), true);
    if (!is_array($endpoints)) {
        return array();
    }
    return $endpoints;
}
示例#6
0
 /**
  * @param $query string A query
  *
  * @return mixed
  */
 protected function _getFromCache($query)
 {
     if ($this->cacheTTL == 0) {
         return null;
     }
     $this->_cacheSetConnection();
     $_existingResult = null;
     if (isset($this->cache_con) && !empty($this->cache_con)) {
         $_existingResult = unserialize($this->cache_con->get(md5($query)));
     }
     return $_existingResult;
 }
示例#7
0
 /**
  */
 protected function _get($keys)
 {
     $keys = array_values($keys);
     $out = array();
     try {
         $data = $this->_predis->mget($keys);
     } catch (Exception $e) {
         /* MGET doesn't work on clusters. */
         $data = array();
         foreach ($keys as $key) {
             $data[$key] = $this->_predis->get($key);
         }
     }
     foreach ($data as $key => $val) {
         $out[$keys[$key]] = is_null($val) ? false : $val;
     }
     return $out;
 }
示例#8
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'));
示例#9
0
switch ($mod) {
    case 'order':
        require_once ROOT_PATH . 'lib/order.php';
        if ($action == 'step1') {
            $order_list = MES_Order::get_order_list();
            $smarty->assign('order_list', $order_list);
            $smarty->display('shoppingcar_new.dwt');
            return;
        } else {
            if ($action == 'step2') {
                //每次结算要记录一个ip防止被刷
                $current_ip = GET_IP();
                $_key = 'checkout_times_' . $current_ip;
                $checkout_times = 0;
                if ($REDIS_CLIENT->exists($_key)) {
                    $checkout_times = intval($REDIS_CLIENT->get($_key));
                }
                $_token = GEN_MES_TOKEN();
                $_SESSION['order_token'] = $_token;
                $smarty->assign('order_token', $_token);
                $smarty->assign('checkout_times', $checkout_times);
                date_default_timezone_set("Etc/GMT-8");
                $time = date('Y-m-d H:i:s', time());
                $smarty->assign('current_time', $time);
                unset($_SESSION['flow_order']['surplus']);
                unset($_SESSION['flow_order']['bonus']);
                unset($_SESSION['flow_order']['bonus_id']);
                unset($_SESSION['flow_order']['bonus_sn']);
                $smarty->display('order_new.dwt');
                return;
            } else {
示例#10
0
 *
 * See https://apacheignite.readme.io/docs/redis for more details on Redis integration.
 */
// Load the library.
require 'predis/autoload.php';
Predis\Autoloader::register();
// Connect.
try {
    $redis = new Predis\Client(array("host" => "localhost", "port" => 11211));
    echo ">>> Successfully connected to Redis. \n";
    // Put entry to cache.
    if ($redis->set('k1', '1')) {
        echo ">>> Successfully put entry in cache. \n";
    }
    // 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";
示例#11
0
 function testResponseReader_EmptyBulkResponse()
 {
     $protocol = new Predis\Protocol\Text\ComposableTextProtocol();
     $connection = new Predis\Network\ComposableStreamConnection(RC::getConnectionParameters(), $protocol);
     $client = new Predis\Client($connection);
     $this->assertTrue($client->set('foo', ''));
     $this->assertEquals('', $client->get('foo'));
     $this->assertEquals('', $client->get('foo'));
 }
        $hash = $this->hash($value);
        $node = $this->getByHash($hash);
        return $node;
    }
    public function hash($value)
    {
        return crc32($value);
    }
    public function getHashGenerator()
    {
        return $this;
    }
}
$options = array('cluster' => function () {
    $distributor = new NaiveDistributor();
    $strategy = new PredisStrategy($distributor);
    $cluster = new PredisCluster($strategy);
    return $cluster;
});
$client = new Predis\Client($multiple_servers, $options);
for ($i = 0; $i < 100; $i++) {
    $client->set("key:{$i}", str_pad($i, 4, '0', 0));
    $client->get("key:{$i}");
}
$server1 = $client->getClientFor('first')->info();
$server2 = $client->getClientFor('second')->info();
if (isset($server1['Keyspace'], $server2['Keyspace'])) {
    $server1 = $server1['Keyspace'];
    $server2 = $server2['Keyspace'];
}
printf("Server '%s' has %d keys while server '%s' has %d keys.\n", 'first', $server1['db15']['keys'], 'second', $server2['db15']['keys']);
//start Check session on memcached is working
session_start();
if (isset($_SESSION[$key])) {
    print "<br/><br/>Username in the session is: {$_SESSION[$key]}";
} else {
    print "<br/><br/>Username is not found in the session. It will be added now.";
    $_SESSION[$key] = 'aamin(session)';
}
//end Check session on memcached is working
//start Test memcached is working
$mem = new Memcached();
$mem->addServer("memcached", 11211);
$result = $mem->get($key);
if ($result) {
    echo "<br/><br/>Username in the memcached is: {$result}";
} else {
    print "<br/><br/>Username is not found in the memcached. It will be added now.";
    $mem->set($key, "aamin(memcached)") or die("Error: Couldn't save anything to memcached...");
}
//end Test memcached is working
//start Test redis is working
require __DIR__ . '/../vendor/autoload.php';
$redis = new Predis\Client('tcp://redis:6379');
$result = $redis->get($key);
if ($result) {
    echo "<br/><br/>Username in the redis is: {$result}";
} else {
    print "<br/><br/>Username is not found in the redis. It will be added now.";
    $redis->set($key, "aamin(redis)") or die("Error: Couldn't save anything to redis...");
}
//end Test redis is working
示例#14
0
 public static function getTMProps($job_data)
 {
     try {
         $redisHandler = new Predis\Client(INIT::$REDIS_SERVERS);
         $redisHandler->get(1);
         //ping established connection
     } catch (Exception $e) {
         $redisHandler = null;
         Log::doLog($e->getMessage());
         Log::doLog("No Redis server(s) available.");
     }
     if (isset($redisHandler) && !empty($redisHandler)) {
         $_existingResult = $redisHandler->get("project_data_for_job_id:" . $job_data['id']);
         if (!empty($_existingResult)) {
             return unserialize($_existingResult);
         }
     }
     $projectData = getProjectJobData($job_data['id_project']);
     $result = array('project_id' => $projectData[0]['pid'], 'project_name' => $projectData[0]['pname'], 'job_id' => $job_data['id']);
     if (isset($redisHandler) && !empty($redisHandler)) {
         $redisHandler->setex("project_data_for_job_id:" . $job_data['id'], 60 * 60 * 24 * 15, serialize($result));
     }
     return $result;
 }
while (time() < $start_time + $time_limit) {
    /* ... perorm BLPOP command ... */
    /* ... process jobs when received ... */
}
/* ... will quit once the time limit has been reached ... */
/*
 * Assigning Worker IDs & Monitoring
 * 
 * Usage: php worker.php 1
 */
// Gets the worker ID from the command line argument
$worker_id = $argv[1];
// Setting the Worker's Status
$predis->hset('worker.status', $worker_id, 'Started');
// Set the last time this worker checked in, use this to
// help determine when scripts die
$predis->hset('worker.status.last_time', $worker_id, time());
/* 
 * Using Versions to Check for Reloads
 */
$version = $predis->get('worker.version');
// i.e. number: 6
while (time() < $start_time + $time_limit) {
    /* ... check for jobs and process them ... */
    /* ... then, at the very end of the while ... */
    if ($predis->get('worker.version') != $version) {
        echo "New Version Detected... \n";
        echo "Reloading... \n";
        exit;
    }
}
示例#16
0
<?php

set_include_path('.:/usr/local/lib/php');
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'Predis/Autoloader.php';
Predis\Autoloader::register();
if (isset($_GET['cmd']) === true) {
    $host = 'redis-master';
    if (getenv('GET_HOSTS_FROM') == 'env') {
        $host = getenv('REDIS_MASTER_SERVICE_HOST');
    }
    header('Content-Type: application/json');
    if ($_GET['cmd'] == 'set') {
        $client = new Predis\Client(['scheme' => 'tcp', 'host' => $host, 'port' => 6379]);
        $client->set($_GET['key'], $_GET['value']);
        print '{"message": "Updated"}';
    } else {
        $host = 'redis-slave';
        if (getenv('GET_HOSTS_FROM') == 'env') {
            $host = getenv('REDIS_SLAVE_SERVICE_HOST');
        }
        $client = new Predis\Client(['scheme' => 'tcp', 'host' => $host, 'port' => 6379]);
        $value = $client->get($_GET['key']);
        print '{"data": "' . $value . '"}';
    }
} else {
    phpinfo();
}
示例#17
0
<?php

/*
 * This file is part of the Predis package.
 *
 * (c) Daniele Alessandri <*****@*****.**>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
require 'SharedConfigurations.php';
// simple set and get scenario
$redis = new Predis\Client($single_server);
$redis->set('library', 'predis');
$retval = $redis->get('library');
var_dump($retval);
/* OUTPUT
string(6) "predis"
*/
示例#18
0
        $timestamp = $timestamp_eu;
        $timestamp_us = strtotime(str_replace('-', '/', $matches[1]));
        if ($timestamp_eu == 0 || $timestamp_eu > time()) {
            $timestamp = $timestamp_us;
        } else {
            if ($timestamp_us != 0 && $timestamp_us <= time() && $timestamp_us > $timestamp_eu) {
                $timestamp = $timestamp_us;
            }
        }
    }
    return $timestamp;
}
header("Content-type: application/rss+xml");
include 'config.php';
$redis = new Predis\Client();
$last_build_date = $redis->get("last_build_date");
$podcastFiles = scandir("./" . $podcast_directory);
date_default_timezone_set("Europe/Berlin");
foreach ($podcastFiles as $podcast) {
    if (substr($podcast, 0, 1) == ".") {
        continue;
    }
    $current_track = new track();
    if ($current_track->load($podcast)) {
        $tracks[] = $current_track;
        continue;
    }
    // not in database
    $last_build_date = time();
    $timestamp = timestamp_from_preg('/(\\d\\d-\\d\\d-\\d\\d\\d\\d)/', $podcast);
    if ($timestamp == 0) {
示例#19
0
#!/usr/bin/env php
<?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');
示例#20
0
文件: index.php 项目: wukon/101nccu
    </div>
	<!-- end 預覽縮圖 div -->
	<!-- 上傳表單,選擇檔案後 onchange 會改變預覽圖案 -->
    <form action="" method="post" enctype="multipart/form-data" name="form1" id="form1"> 
	    <input class="but" id="theFile" name="theFile" type="file" onchange="ImagesProview(this)" />
	    <input name="Submit" type="submit" value="上傳">
    </form>
    <!-- end 上傳表單 -->
    <br>
    <?php 
/* 用 foreach 把 S3 所有的圖讀出來顯示,若為資料夾就掉過 */
// Get the contents of our bucket
$contents = $s3->getBucket('nccus3');
foreach ($contents as $file) {
    $fname = $file['name'];
    $value = $redis->get($fname);
    $num = strrpos($fname, "/");
    // if $file is a directory path
    if ($num === false) {
        $furl = "http://nccus3.s3.amazonaws.com/" . $fname;
        echo "<a href=\"image_cache.php?fn={$fname}\" alt=\"{$fname}\"><img id=\"thumb\" src=\"{$furl}\" /></a>";
    }
}
/* end 讀圖 */
?>
	<!-- javascript 縮圖程式 -->
	<script type="text/javascript">
		var isIE=function() {
		   return (document.all) ? true : false;
		}
<?php

/*
 * This file is part of the Predis package.
 *
 * (c) Daniele Alessandri <*****@*****.**>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
require __DIR__ . '/shared.php';
$client = new Predis\Client($single_server);
// Plain old SET and GET example...
$client->set('library', 'predis');
$response = $client->get('library');
var_export($response);
echo PHP_EOL;
/* OUTPUT: 'predis' */
// Redis has the MSET and MGET commands to set or get multiple keys in one go,
// cases like this Predis accepts arguments for variadic commands both as a list
// of arguments or an array containing all of the keys and/or values.
$mkv = array('uid:0001' => '1st user', 'uid:0002' => '2nd user', 'uid:0003' => '3rd user');
$client->mset($mkv);
$response = $client->mget(array_keys($mkv));
var_export($response);
echo PHP_EOL;
/* OUTPUT:
  array (
  0 => '1st user',
  1 => '2nd user',
  2 => '3rd user',
示例#22
0
文件: Client.php 项目: cargomedia/cm
 /**
  * @param string $key
  * @return string|false
  */
 public function get($key)
 {
     $value = $this->_redis->get($key);
     return is_null($value) ? false : $value;
 }
示例#23
0
        // 	$redis->set("email_" . $hash, true);
        // }
        // return key
        return json_encode(array("type" => "success", "key" => $hash));
    } catch (Exception $E) {
        return array("type" => "error", "message" => $E->getMessage());
    }
});
$app->get('/getInfo', function () {
    try {
        // spin up redis
        $redis = new Predis\Client();
        // register the user
        $RedisData = $redis->keys("*");
        $dataArray = [];
        // return key
        foreach ($RedisData as $key) {
            if (strlen($key) != 32) {
                continue;
            }
            $jsonData = $redis->get($key);
            if (!empty($jsonData)) {
                $dataArray[$key] = json_decode($jsonData);
            }
        }
        echo "<pre>" . print_r($dataArray, true) . "</pre>";
        return;
    } catch (Exception $E) {
        return array("type" => "error", "message" => $E->getMessage());
    }
});
        $this->_nodesCount++;
    }
    public function remove($node)
    {
        $this->_nodes = array_filter($this->_nodes, function ($n) use($node) {
            return $n !== $node;
        });
        $this->_nodesCount = count($this->_nodes);
    }
    public function get($key)
    {
        $count = $this->_nodesCount;
        if ($count === 0) {
            throw new RuntimeException('No connections');
        }
        return $this->_nodes[$count > 1 ? abs(crc32($key) % $count) : 0];
    }
    public function generateKey($value)
    {
        return crc32($value);
    }
}
$options = array('key_distribution' => new NaiveDistributionStrategy());
$redis = new Predis\Client($multiple_servers, $options);
for ($i = 0; $i < 100; $i++) {
    $redis->set("key:{$i}", str_pad($i, 4, '0', 0));
    $redis->get("key:{$i}");
}
$server1 = $redis->getClientFor('first')->info();
$server2 = $redis->getClientFor('second')->info();
printf("Server '%s' has %d keys while server '%s' has %d keys.\n", 'first', $server1['db15']['keys'], 'second', $server2['db15']['keys']);
 /**
  * Decrement a Redis counter by the amount specified
  *
  * @param  string $key
  * @param  int    $offset
  * @param  string $group
  * @return bool
  */
 public function decrement($key, $offset = 1, $group = 'default')
 {
     $derived_key = $this->build_key($key, $group);
     $offset = (int) $offset;
     // If group is a non-Redis group, save to internal cache, not Redis
     if (in_array($group, $this->no_redis_groups) || !$this->redis_status()) {
         $value = $this->get_from_internal_cache($derived_key, $group);
         $value -= $offset;
         $this->add_to_internal_cache($derived_key, $value);
         return true;
     }
     // Save to Redis
     $result = $this->parse_predis_response($this->redis->decrBy($derived_key, $offset));
     $this->add_to_internal_cache($derived_key, (int) $this->redis->get($derived_key));
     return $result;
 }
示例#26
0
    public function readResponse(Predis\ICommand $command)
    {
        $reply = parent::readResponse($command);
        $this->storeDebug($command, '<-');
        return $reply;
    }
    public function getDebugBuffer()
    {
        return $this->_debugBuffer;
    }
}
$parameters = new Predis\ConnectionParameters($single_server);
$connection = new SimpleDebuggableConnection($parameters);
$redis = new Predis\Client($connection);
$redis->set('foo', 'bar');
$redis->get('foo');
$redis->info();
print_r($connection->getDebugBuffer());
/* OUTPUT:
Array
(
    [0] => SELECT 15 -> 127.0.0.1:6379 [0.0008s]
    [1] => SELECT 15 <- 127.0.0.1:6379 [0.0012s]
    [2] => SET foo -> 127.0.0.1:6379 [0.0014s]
    [3] => SET foo <- 127.0.0.1:6379 [0.0014s]
    [4] => GET foo -> 127.0.0.1:6379 [0.0016s]
    [5] => GET foo <- 127.0.0.1:6379 [0.0018s]
    [6] => INFO -> 127.0.0.1:6379 [0.002s]
    [7] => INFO <- 127.0.0.1:6379 [0.0025s]
)
*/
示例#27
0
// scenarios. The only but relevant difference with a basic replication scenario
// is that sentinel servers can manage the master server and its slaves based on
// their state, which means that they are able to provide an authoritative and
// updated configuration to clients thus avoiding static configurations for the
// replication servers and their roles.
// Instead of connection parameters pointing to redis nodes, we provide a list
// of instances of redis-sentinel. Users should always provide a timeout value
// low enough to not hinder operations just in case a sentinel is unreachable
// but Predis uses a default value of 100 milliseconds for sentinel parameters
// without an explicit timeout value.
//
// NOTE: in real-world scenarios sentinels should be running on different hosts!
$sentinels = array('tcp://127.0.0.1:5380?timeout=0.100', 'tcp://127.0.0.1:5381?timeout=0.100', 'tcp://127.0.0.1:5382?timeout=0.100');
$client = new Predis\Client($sentinels, array('replication' => 'sentinel', 'service' => 'mymaster'));
// Read operation.
$exists = $client->exists('foo') ? 'yes' : 'no';
$current = $client->getConnection()->getCurrent()->getParameters();
echo "Does 'foo' exist on {$current->role}? {$exists}.", PHP_EOL;
// Write operation.
$client->set('foo', 'bar');
$current = $client->getConnection()->getCurrent()->getParameters();
echo "Now 'foo' has been set to 'bar' on {$current->role}!", PHP_EOL;
// Read operation.
$bar = $client->get('foo');
$current = $client->getConnection()->getCurrent()->getParameters();
echo "We fetched 'foo' from {$current->role} and its value is '{$bar}'.", PHP_EOL;
/* OUTPUT:
Does 'foo' exist on slave-127.0.0.1:6381? yes.
Now 'foo' has been set to 'bar' on master!
We fetched 'foo' from master and its value is 'bar'.
*/
示例#28
0
function S($name, $value = '', $time = '')
{
    $client = new Predis\Client($GLOBALS['redisConfig']);
    if ('' === $value) {
        // 获取缓存
        return json_decode($client->get($name), true);
    } elseif (is_null($value)) {
        // 删除缓存
        return $client->set($name, null);
    } else {
        // 缓存数据
        $value = json_encode($value);
        if (empty($time)) {
            return $client->set($name, $value);
        } else {
            return $client->setex($name, $time, $value);
        }
    }
}
示例#29
0
        $this->storeDebug($command, '->');
    }
    public function readResponse(CommandInterface $command)
    {
        $response = parent::readResponse($command);
        $this->storeDebug($command, '<-');
        return $response;
    }
    public function getDebugBuffer()
    {
        return $this->debugBuffer;
    }
}
$options = array('connections' => array('tcp' => 'SimpleDebuggableConnection'));
$client = new Predis\Client($single_server, $options);
$client->set('foo', 'bar');
$client->get('foo');
$client->info();
var_export($client->getConnection()->getDebugBuffer());
/* OUTPUT:
array (
  0 => 'SELECT 15 -> 127.0.0.1:6379 [0.0008s]',
  1 => 'SELECT 15 <- 127.0.0.1:6379 [0.001s]',
  2 => 'SET foo -> 127.0.0.1:6379 [0.001s]',
  3 => 'SET foo <- 127.0.0.1:6379 [0.0011s]',
  4 => 'GET foo -> 127.0.0.1:6379 [0.0013s]',
  5 => 'GET foo <- 127.0.0.1:6379 [0.0015s]',
  6 => 'INFO -> 127.0.0.1:6379 [0.0019s]',
  7 => 'INFO <- 127.0.0.1:6379 [0.0022s]',
)
*/
示例#30
0
	$i_visits = 'nan';

	try {
		$redis = new Predis\Client(array(
			'scheme' => 'tcp',
			'host' => 'ack-monitor',
			//'host' => '104.155.23.31',
			'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'
	));