예제 #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
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";
    }
}
예제 #3
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);
    }
}
예제 #4
0
 /**
  * Store a key/value pair in the cache
  * @param $key string The key to store as
  * @param $value object The value to store
  * @param $expire int The number of seconds to expire in, 0 for forever
  * @return TRUE on success and FALSE on failure
  */
 public function set($key, $value, $expire = 0)
 {
     if (!$this->isEnabled()) {
         return false;
     }
     if (!$this->attemptedConnection) {
         $this->connect();
     }
     // Check for flags
     if ($expire == CACHE_UNTIL_NEXT_GRAPH) {
         $expire = strtotime('+30 minutes', getLastGraphEpoch());
     }
     $this->handle->set($key, gzencode($value));
     if ($expire > 0) {
         $this->handle->expireat($key, $expire);
     }
     return true;
 }
예제 #5
0
파일: Predis.php 프로젝트: jubinpatel/horde
 /**
  */
 protected function _set($key, $val, $opts)
 {
     if (!empty($opts['replace']) && !$this->_predis->exists($key)) {
         return false;
     }
     /* Can't use SETEX, since 2.0 server is not guaranteed. */
     if (!$this->_predis->set($key, $val)) {
         return false;
     }
     if (!empty($opts['expire'])) {
         $this->_predis->expire($key, $opts['expire']);
     }
     return true;
 }
예제 #6
0
{
    $xpath = new DOMXPath($xml);
    $xpath->registerNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");
    $xpath->registerNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
    //$query = "/samlp:Response/saml:Assertion/saml:Subject/saml:NameID";
    $query = "/samlp:Response/saml:Assertion/saml:AttributeStatement/saml:Attribute";
    $entries = $xpath->query($query);
    return $entries->item(0)->nodeValue;
}
function genToken()
{
    return mt_rand() . mt_rand() . mt_rand() . mt_rand() . mt_rand();
}
if (is_valid($document, $x509certificate)) {
    //echo htmlentities($documentStr);
    $authedUser = get_nameid($document);
    $desiredUser = $_COOKIE['userId'];
    if ($authedUser != $desiredUser) {
        echo "Sorry, you want to log in to '{$desiredUser}' but it looks like you are '{$authedUser}'. Please go away.";
        die;
    } else {
        $token = genToken();
        $categories = json_encode(explode(',', $_COOKIE['scope']));
        $redis->set('token:' . $_COOKIE['userId'] . ':' . $token, $categories);
        //echo 'redis->set(token:'.$_COOKIE['userId'].':'.$token.', '.$categories;
        //echo 'Location: '.$_COOKIE['redirectUri'].'#access_token='.urlencode($token);
        header('Location: ' . $_COOKIE['redirectUri'] . '#access_token=' . urlencode($token));
    }
} else {
    echo '<!DOCTYPE html><head><meta charset="utf-8"><title>No go</title></head><body>' . 'Sorry, no access.' . '</body></html>';
}
예제 #7
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);
        }
    }
}
예제 #8
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]
)
 /**
  * Sets a value in cache.
  *
  * The value is set whether or not this key already exists in Redis.
  *
  * @param   string $key        The key under which to store the value.
  * @param   mixed  $value      The value to store.
  * @param   string $group      The group value appended to the $key.
  * @param   int    $expiration The expiration time, defaults to 0.
  * @return  bool               Returns TRUE on success or FALSE on failure.
  */
 public function set($key, $value, $group = 'default', $expiration = 0)
 {
     $derived_key = $this->build_key($key, $group);
     // If group is a non-Redis group, save to internal cache, not Redis
     if (in_array($group, $this->no_redis_groups) || !$this->can_redis()) {
         $this->add_to_internal_cache($derived_key, $value);
         return true;
     }
     // Save to Redis
     $expiration = abs(intval($expiration));
     if ($expiration) {
         $result = $this->parse_predis_response($this->redis->setex($derived_key, $expiration, $value));
     } else {
         $result = $this->parse_predis_response($this->redis->set($derived_key, $value));
     }
     return $result;
 }
예제 #10
0
 /**
  * Sets a value in cache.
  *
  * The value is set whether or not this key already exists in Redis.
  *
  * @param   string $key        The key under which to store the value.
  * @param   mixed  $value      The value to store.
  * @param   string $group      The group value appended to the $key.
  * @param   int    $expiration The expiration time, defaults to 0.
  * @return  bool               Returns TRUE on success or FALSE on failure.
  */
 public function set($key, $value, $group = 'default', $expiration = 0)
 {
     $derived_key = $this->build_key($key, $group);
     $result = true;
     // save if group not excluded from redis and redis is up
     if (!in_array($group, $this->no_redis_groups) && $this->redis_status()) {
         $expiration = $this->validate_expiration($expiration);
         if ($expiration) {
             $result = $this->parse_predis_response($this->redis->setex($derived_key, $expiration, maybe_serialize($value)));
         } else {
             $result = $this->parse_predis_response($this->redis->set($derived_key, maybe_serialize($value)));
         }
     }
     // if the set was successful, or we didn't go to redis
     if ($result) {
         $this->add_to_internal_cache($derived_key, $value);
     }
     return $result;
 }
예제 #11
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 __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',
예제 #12
0
 */
/**
 * To execute this script, you need to have Predis extension installed and Ignite running.
 * See https://github.com/nrk/predis for Predis details.
 *
 * 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.
예제 #13
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');
예제 #14
0
파일: index.php 프로젝트: wukon/101nccu
 $fileName = $_FILES['theFile']['name'];
 $fileTempName = $_FILES['theFile']['tmp_name'];
 $path_ext = pathinfo($fileName, PATHINFO_EXTENSION);
 // get filename extension
 $ext = strtolower($path_ext);
 $data = file_get_contents($fileTempName);
 switch ($ext) {
     case 'jpg':
     case 'jpeg':
     case 'png':
     case 'gif':
         // get file content
         $data = file_get_contents($fileTempName);
         // caching using local file name as key
         //$m->set($fileName,$data,0);
         $redis->set($fileName, $data);
         // 範例:把目前時間當成 message 送給 input queue
         // (縮圖程式的 message 內容改為圖片位置以及希望得到的 size 等資訊)
         date_default_timezone_set('Asia/Taipei');
         $send = $sqs->sendMessage($input_queue, $fileName);
         echo "Message Send: <br>";
         print_r($send);
         echo "<br>";
         // saving file on S3
         if ($s3->putObjectFile($fileTempName, "nccus3", $fileName, S3::ACL_PUBLIC_READ)) {
             echo "We successfully uploaded your file.";
         } else {
             echo "Something went wrong while uploading your file... sorry.";
         }
         break;
     default:
예제 #15
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"
*/
예제 #16
0
파일: Redis.php 프로젝트: JerryCR/php-2
 /**
  * Performs the test.
  *
  * @return \Jyxo\Beholder\Result
  */
 public function run()
 {
     // The redis extension or Predis library is required
     if (!extension_loaded('redis') && !class_exists('\\Predis\\Client')) {
         return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::NOT_APPLICABLE, 'Extension redis or Predis library required');
     }
     $random = md5(uniqid(time(), true));
     $key = 'beholder-' . $random;
     $value = $random;
     // Status label
     $description = (false !== filter_var($this->host, FILTER_VALIDATE_IP) ? gethostbyaddr($this->host) : $this->host) . ':' . $this->port . '?database=' . $this->database;
     // Connection
     if (extension_loaded('redis')) {
         $redis = new \Redis();
         if (false === $redis->connect($this->host, $this->port, 2)) {
             return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::FAILURE, sprintf('Connection error %s', $description));
         }
     } else {
         $redis = new \Predis\Client(array('host' => $this->host, 'port' => $this->port));
         if (false === $redis->connect()) {
             return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::FAILURE, sprintf('Connection error %s', $description));
         }
     }
     // Select database
     if (false === $redis->select($this->database)) {
         return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::FAILURE, sprintf('Database error %s', $description));
     }
     // Saving
     if (false === $redis->set($key, $value)) {
         if ($redis instanceof \Redis) {
             $redis->close();
         } else {
             $redis->quit();
         }
         return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::FAILURE, sprintf('Write error %s', $description));
     }
     // Check
     $check = $redis->get($key);
     if (false === $check || $check !== $value) {
         if ($redis instanceof \Redis) {
             $redis->close();
         } else {
             $redis->quit();
         }
         return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::FAILURE, sprintf('Read error %s', $description));
     }
     // Deleting
     if (false === $redis->del($key)) {
         if ($redis instanceof \Redis) {
             $redis->close();
         } else {
             $redis->quit();
         }
         return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::FAILURE, sprintf('Delete error %s', $description));
     }
     // Disconnect
     if ($redis instanceof \Redis) {
         $redis->close();
     } else {
         $redis->quit();
     }
     // OK
     return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::SUCCESS, $description);
 }
예제 #17
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     // Start by printing some information about what the version
     $this->info('Running SeAT ' . \Config::get('seat.version') . ' Diagnostics');
     $this->line('');
     // It is important to run the command as the user that the workers are running as.
     // This way, the checks that ensure file permissions are right are executed
     // properly. If this is not the case, notify the user
     $this->comment('If you are not already doing so, it is recommended that you run this as the user the workers are running as.');
     $this->comment('Eg: `sudo -u apache php artisan seat:diagnose`.');
     $this->comment('This helps to check whether the permissions are correct.');
     $this->line('');
     // Go ahead and get the configuration information using
     // the \Config helper and print that
     $this->info('SeAT configuration:');
     if (\Config::get('app.debug')) {
         $this->comment('[warning] Debug Mode On: Yes. It is recommended that you set this to false in app/config/app.php');
     } else {
         $this->line('[ok] Debug Mode On: No');
     }
     $this->line('Url: ' . \Config::get('app.url'));
     $this->line('Failed API limit: ' . \Config::get('seat.ban_limit'));
     $this->line('Ban count time: ' . \Config::get('seat.ban_grace') . ' minutes');
     $this->line('');
     // Check that the log files are writable
     $this->info('Logging:');
     if (is_writable(storage_path() . '/logs/laravel.log')) {
         $this->line('[ok] ' . storage_path() . '/logs/laravel.log is writable.');
     } else {
         $this->error('[error] ' . storage_path() . '/logs/laravel.log is not writable.');
     }
     $this->line('');
     // Grab the database configurations from the config,
     // obviously hashing out the password
     $this->info('Database configuration:');
     $this->line('Database driver: ' . \Config::get('database.default'));
     $this->line('MySQL Host: ' . \Config::get('database.connections.mysql.host'));
     $this->line('MySQL Database: ' . \Config::get('database.connections.mysql.database'));
     $this->line('MySQL Username: '******'database.connections.mysql.username'));
     $this->line('MySQL Password: '******'*', strlen(\Config::get('database.connections.mysql.password'))));
     $this->line('');
     // Test the database connection. An exception will be
     // thrown if this fails, so we can catch it and
     // warn accordingly
     $this->info('Database connection test...');
     try {
         $this->line('[ok] Successfully connected to database `' . \DB::connection()->getDatabaseName() . '` (did not test schema)');
     } catch (\Exception $e) {
         $this->error('[error] Unable to obtain a MySQL connection. The error was: ' . $e->getCode() . ': ' . $e->getMessage());
     }
     $this->line('');
     // Get the Redis cache configuration and print it
     $this->info('Redis configuration:');
     $this->line('Redis Host: ' . \Config::get('database.redis.default.host'));
     $this->line('Redis Port: ' . \Config::get('database.redis.default.port'));
     $this->line('');
     // Test using the Redis cache. Failure should again
     // throw an exception, so catch this also and
     // warn accordingly.
     $this->info('Redis connection test...');
     // Create a random string as the key we will try
     // to read and write
     $key_test = str_random(40);
     try {
         // Make use of the underlying Predis library to
         // connect directly to the Redis cache
         $redis = new \Predis\Client(array('host' => \Config::get('database.redis.default.host'), 'port' => \Config::get('database.redis.default.port')));
         // Set a new key, and modify its expiry
         $redis->set($key_test, \Carbon\Carbon::now());
         $redis->expire($key_test, 10);
         $this->line('[ok] Successfully set the key: ' . $key_test . ' and set it to expire in 10 seconds');
         // Attempt to read the newly place key
         $value_test = $redis->get($key_test);
         $this->line('[ok] Successfully retreived key: ' . $key_test . ' which has value: ' . $value_test);
     } catch (\Exception $e) {
         $this->error('[error] Redis test failed. The last error was: ' . $e->getCode() . ': ' . $e->getMessage());
     }
     $this->line('');
     // Testing Pheal
     $this->info('EVE API call test with phealng...');
     // Bootstrap a new Pheal instance for use
     BaseApi::bootstrap();
     $pheal = new Pheal();
     // Test that Pheal usage is possible by calling the
     // ServerStatus() API
     try {
         $server_status = $pheal->serverScope->ServerStatus();
         $this->line('[ok] Testing the ServerStatus API call returned a response reporting ' . $server_status->onlinePlayers . ' online players, with the result cache expiring ' . \Carbon\Carbon::parse($server_status->cached_until)->diffForHumans());
     } catch (\Exception $e) {
         $this->error('[error] API Call test failed. The last error was: ' . $e->getCode() . ': ' . $e->getMessage());
     }
     $this->line('');
 }
예제 #18
0
파일: predis.php 프로젝트: yfix/yf
#!/usr/bin/php
<?php 
$config = ['git_urls' => ['https://github.com/nrk/predis.git' => 'predis/'], 'autoload_config' => ['predis/src/' => 'Predis'], 'example' => function () {
    $client = new Predis\Client(['scheme' => 'tcp', 'host' => getenv('REDIS_HOST') ?: '127.0.0.1', 'port' => getenv('REDIS_PORT') ?: 6379]);
    $client->set('testme_key', 'testme_val');
    $value = $client->get('testme_key');
    print ($value == 'testme_val' ? 'OK' : 'ERROR') . PHP_EOL;
}];
if ($return_config) {
    return $config;
}
require_once __DIR__ . '/_yf_autoloader.php';
new yf_autoloader($config);
예제 #19
0
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/ClashAPI/API.class.php';
date_default_timezone_set('Europe/Berlin');
$redis = new Predis\Client(getenv('REDIS_URL'));
if ($redis->exists('timer')) {
    echo 'Just wait another hour...';
} else {
    $timestamp = date("d.m.Y - H:i");
    $clan = new CoC_Clan("#QVQRYYG");
    $tottroph = 0;
    $totlvl = 0;
    foreach ($clan->getAllMembers() as $clanmember) {
        $member = new CoC_Member($clanmember);
        $league = new CoC_League($member->getLeague());
        $donationsReceivedCalc = $member->getDonationsReceived();
        if ($donationsReceivedCalc == 0) {
            $donationsReceivedCalc++;
        }
        $ratio = $member->getDonations() / $donationsReceivedCalc;
        $tottroph = $tottroph + $member->getTrophies();
        $totlvl = $totlvl + $member->getLevel();
        $clanmem[$member->getClanRank()] = ["rank" => $member->getClanRank(), "prevrank" => $member->getPreviousClanRank(), "name" => $member->getName(), "role" => $member->getRole(), "trophies" => $member->getTrophies(), "donations" => $member->getDonations(), "received" => $member->getDonationsReceived(), "ratio" => number_format($ratio, 2), "level" => $member->getLevel(), "leaguename" => $league->getLeagueName(), "leagueid" => $league->getLeagueId(), "leagueicontn" => $league->getLeagueIcon("tiny"), "leagueiconsm" => $league->getLeagueIcon("small"), "leagueiconmd" => $league->getLeagueIcon("medium")];
    }
    $avgtroph = round($tottroph / $clan->getMemberCount(), 0);
    $avglvl = round($totlvl / $clan->getMemberCount(), 0);
    $clandetails = ["badgesm" => $clan->getBadgeUrl("small"), "badgemd" => $clan->getBadgeUrl("medium"), "badgelg" => $clan->getBadgeUrl("large"), "name" => $clan->getName(), "level" => $clan->getLevel(), "description" => $clan->getDescription(), "wins" => $clan->getWarWins(), "ties" => $clan->getWarTies(), "losses" => $clan->getWarLosses(), "streak" => $clan->getWarWinStreak(), "points" => $clan->getPoints(), "freq" => $clan->getWarFrequency(), "membercount" => $clan->getMemberCount(), "avgtroph" => $avgtroph, "avglvl" => $avglvl, "timestamp" => $timestamp];
    $redis->set('clandetails', serialize($clandetails));
    $redis->set('clanmem', serialize($clanmem));
    $redis->setEx('timer', 5400, '');
}
예제 #20
0
		$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'
	));
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$output = curl_exec($ch);
	curl_close($ch);
예제 #21
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'));
 }
예제 #22
0
        continue;
    }
    // not in database
    $last_build_date = time();
    $timestamp = timestamp_from_preg('/(\\d\\d-\\d\\d-\\d\\d\\d\\d)/', $podcast);
    if ($timestamp == 0) {
        $timestamp = filemtime($podcast_directory . "/" . $podcast);
    }
    $getID3 = new getID3();
    $ThisFileInfo = $getID3->analyze("./" . $podcast_directory . "/" . $podcast);
    $duration = @$ThisFileInfo['playtime_string'];
    $filename = str_replace("_", " ", $podcast);
    if (preg_match('/.*?-(.*?)-(.*?)-.*?/', $filename, $matches)) {
        $current_track->content["author"] = trim($matches[1]);
        $current_track->content["title"] = trim($matches[2]);
    }
    $current_track->content["subtitle"] = basename($podcast, ".mp3");
    $current_track->content["filesize"] = filesize("./" . $podcast_directory . "/" . $podcast);
    $current_track->content["url"] = $base_url . "/" . $podcast_directory . "/" . $podcast;
    $current_track->content["duration"] = $duration;
    $current_track->content["timestamp"] = $timestamp;
    $tracks[] = $current_track;
    $current_track->save($podcast);
}
$redis->set("last_build_date", $last_build_date);
uasort($tracks, "by_custom_date");
include 'header.php';
foreach ($tracks as $track) {
    $track->get_xml();
}
include 'footer.php';
예제 #23
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();
}
//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
예제 #25
0
 */
$app->post('/register', function (Request $Request) {
    // create hash
    $hash = md5($Request->email . $Request->firstName . $Request->lastName . $Request->position);
    // gather data
    $data = array('email' => $Request->email, 'firstName' => $Request->firstName, 'lastName' => $Request->lastName, 'position' => $Request->position, 'intersted' => $Request->intersted);
    foreach ($data as $key => $value) {
        if ($key != 'intersted' && empty($value)) {
            return json_encode(array("type" => "invalid", "field" => $key));
        }
    }
    try {
        // spin up redis
        $redis = new Predis\Client();
        // register the user
        $redis->set($hash, json_encode($data));
        // if(!$redis->exists("email_" . $hash)){
        // 	mail($Request->email, "Red Ventures - Sphero Registration", "<p>Thanks for registering, " . $Request->firstName .".<br /><br />Your API key is " . $hash . " and the docs to how to send the shpero commands is located <a href='sphero-api.hopto.org/docs' target='_blank'>here</a>. Have fun!</p>");
        // 	$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
        $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']);
        $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']);
예제 #28
0
<?php

require 'Predis/Autoloader.php';
Predis\Autoloader::register();
$redis = new Predis\Client(array('host' => '127.0.0.1'));
$redis->set('counter', 0);
$redis->incrBy('counter', 7);
$counter = $redis->get('counter');
print $counter;
예제 #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
파일: Client.php 프로젝트: cargomedia/cm
 /**
  * @param string $key
  * @param string $value
  * @return string|null
  */
 public function set($key, $value)
 {
     $this->_redis->set($key, $value);
 }