<?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)
$sessionId = $app->request->params('session_id'); $helpSessionKey = PREFIX_HELP_SESSION_KEY . $sessionId; // Validation // Check to see that the help session exists $redisResponse = $redis->exists($helpSessionKey); if (!handleRedisError($redisResponse, $app, 'Não foi possível verificar se a sessão de vídeo chat já existe.')) { return; } $exists = (bool) $redisResponse; if (!$exists) { $app->response->setStatus(400); $app->response->setBody('Uma session_id inválida foi criada.'); return; } // Add the help session to the queue $redisResponse = $redis->rpush(HELP_QUEUE_KEY, $helpSessionKey); if (!handleRedisError($redisResponse, $app, 'Não foi possível adicionar a sessão à fila de atendimento.')) { return; } $queueId = $helpSessionKey; $responseData = array('queueId' => $queueId); $app->response->headers->set('Content-Type', 'application/json'); $app->response->setBody(json_encode($responseData)); }); // Representative delivers serivce // // Dequeue from service queue and assign to representative (FIFO). If there is a customer on the // queue, respond with the help session data and additional data needed to connect. If there isn't // a customer available on the queue, respond with status code 204 NO CONTENT. // // Response: (JSON encoded)
/** * 保存记录至redis * @access private * @param string $value 保存值 * @return boolean 成功返回true,失败返回false */ private function save_item_in_redis($value = '') { require './include/Predis/Autoloader.php'; Predis\Autoloader::register(); try { $r = new Predis\Client(); $r->connect('127.0.0.1', 6379); $my_log_len = $r->llen($this->config->item('encryption_key')); if ($my_log_len < 21) { $r->rpush($this->config->item('encryption_key'), $value); } else { $r->lpop($this->config->item('encryption_key')); $r->rpush($this->config->item('encryption_key'), $value); } return TRUE; } catch (Exception $e) { echo $e->getMessage(); return FALSE; } }
function notifyRedis($crisisID, $attributeIDs) { $json = "{crisis_id:{$crisisID}, attributes:[" . implode(',', $attributeIDs) . "]}"; $redis = new Predis\Client('tcp://127.0.0.1:6379'); $redis->rpush("training_sample_info_stream", $json); }
public static function create_socket_server($host = "0.0.0.0", $port = 3465) { //Create a UDP socket if (!($sock = socket_create(AF_INET, SOCK_DGRAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Couldn't create socket: [{$errorcode}] {$errormsg} \n"); } echo "Socket created \n"; // Bind the source address if (!socket_bind($sock, $host, $port)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not bind socket : [{$errorcode}] {$errormsg} \n"); } echo "Socket bind OK \n"; // Connect to Redis. $redis = new \Predis\Client(); // Do some communication, this loop can handle multiple clients while (true) { //Receive some data $r = socket_recvfrom($sock, $buf, Eventsd::MaxUDPPacket, 0, $remote_ip, $remote_port); $redis->rpush('events_que', $buf); unset($event, $buf, $remote_ip, $remote_port); } socket_close($sock); }
* code snippits used in the post. */ /* * Connecting to Redis */ const REDIS_HOST = '127.0.0.1'; const REDIS_PORT = 6379; $predis = new Predis\Client(array('scheme' => 'tcp', 'host' => REDIS_HOST, 'port' => REDIS_PORT)); /* * Adding items to the queue */ $job = new stdClass(); $job->id = 1; $job->report = 'general'; // Add the job to the high priority queue $predis->rpush('queue.priority.high', json_encode($job)); // Or, you could add it to the normal or low priority queue. $predis->rpush('queue.priority.normal', json_encode($job)); $predis->rpush('queue.priority.low', json_encode($job)); /* * Simple Continuous While Loop */ // Always True while (1) { /* ... perform tasks here ... */ } /* * Checking the Queue */ $job = $predis->blpop('queue.priority.high', 'queue.priority.normal', 'queue.priority.low', 10); /*
<?php require 'vendor/autoload.php'; Predis\Autoloader::register(); $client = new Predis\Client(array('host' => '127.0.0.1', 'port' => 6379), array('prefix' => 'php:')); $client->lpush('blocking:queue', 'first'); $client->lpush('blocking:queue', 'second'); $client->blpop(['blocking:queue'], 0); # array('php:blocking:queue', 'second') $client->brpop(['blocking:queue'], 0); # array('php:blocking:queue', 'first') $client->rpush('blocking:source', 'message'); $client->brpoplpush('blocking:source', 'blocking:destination', 0); # 'message'
<?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 list * * @author changdi */ require '../shared.php'; $predis = new Predis\Client($single_server); //var_dump($predis->rpush('list-key','last')); //var_dump($predis->lpush('list-key','first')); //var_dump($predis->rpush('list-key','new last')); var_dump($predis->lrange('list-key', 0, -1)); //var_dump($predis->lpop('list-key')); //var_dump($predis->rpop('list-key')); var_dump($predis->lrange('list-key', 0, -1)); var_dump($predis->rpush('list-key', 'a', 'b', 'c')); var_dump($predis->lrange('list-key', 0, -1)); var_dump($predis->ltrim('list-key', 2, -1)); var_dump($predis->lrange('list-key', 0, -1));
$jobs_to_create = 10; // Default } echo "Creating Jobs: {$jobs_to_create} \n"; $messages_str = file_get_contents('randomsayings.txt'); $messages = explode("\n", $messages_str); $messages_count = count($messages); $count = 0; while ($count < $jobs_to_create) { $count++; $job = new stdClass(); $job->wait = rand(0, 500000); $job->loops = rand(2, 10); $job->message = $messages[rand(0, $messages_count - 1)]; $job_json = json_encode($job); // Randomly select which queue to use $rand = rand(0, 10); $queue_name = ''; if ($rand >= 10) { $queue_name = 'queue.priority.high'; } else { if ($rand >= 6) { $queue_name = 'queue.priority.normal'; } else { $queue_name = 'queue.priority.low'; } } $predis->rpush($queue_name, $job_json); echo "Job [{$count}] Generated. \n"; } echo "Done!\nGoodbye...\n";
$publishCommand[] = escapeshellarg('--no-heads'); $publishCommand[] = escapeshellarg(sprintf('--tags=%s', $matches[1])); } elseif (preg_match('/refs\\/heads\\/(.+)$/', $ref, $matches)) { $publishCommand[] = escapeshellarg('--no-tags'); $publishCommand[] = escapeshellarg(sprintf('--heads=%s', $matches[1])); } else { print sprintf('Skipping request for URL %s (unexpected reference detected: %s)', $data['repository']['url'], $ref) . "\n"; $redis->lrem('dflydev-git-subsplit:processing', 1, $body); $redis->lpush('dflydev-git-subspilt:failures', json_encode($data)); continue; } $repositoryUrl = isset($project['repository-url']) ? $project['repository-url'] : $project['url']; print sprintf('Processing subsplit for %s (%s)', $name, $ref) . "\n"; $projectWorkingDirectory = $config['working-directory'] . '/' . $name; if (!file_exists($projectWorkingDirectory)) { print sprintf('Creating working directory for project %s (%s)', $name, $projectWorkingDirectory) . "\n"; mkdir($projectWorkingDirectory, 0750, true); } $command = implode(' && ', array(sprintf('cd %s', $projectWorkingDirectory), sprintf('( git subsplit init %s || true )', $repositoryUrl), 'git subsplit update', implode(' ', $publishCommand))); passthru($command, $exitCode); if (0 !== $exitCode) { print sprintf('Command %s had a problem, exit code %s', $command, $exitCode) . "\n"; $redis->lrem('dflydev-git-subsplit:processing', 1, $body); $redis->lpush('dflydev-git-subspilt:failures', json_encode($data)); continue; } $redis->lrem('dflydev-git-subsplit:processing', 1, $body); $redis->rpush('dflydev-git-subsplit:processed', json_encode($data)); } $seconds = time() - $start; throw new \RuntimeException(sprintf('Something strange happened after %s seconds', $seconds));
public static function pushTailAndReturn(Predis\Client $client, $keyName, array $values, $wipeOut = 0) { if ($wipeOut == true) { $client->del($keyName); } foreach ($values as $value) { $client->rpush($keyName, $value); } return $values; }
Predis\Autoloader::register(); $redis = new Predis\Client($_config['redis_server']); //读取case目录的文件,将测试用例写到队列。 $fileArray = scandir($_config['case_dir']); foreach ($fileArray as $file) { if ($file == '.' || $file == '..') { continue; } $count = 0; $testcase = new testcase($_config['case_dir'] . $file); $case_data = $testcase->getdata(); //插入队列 if (is_array($case_data)) { foreach ($case_data as $v) { // echo json_encode($v)."\n"; $redis->rpush($_config['queue_name'], json_encode($v)) . "\n"; $count++; } } else { $redis->rpush($_config['queue_name'], json_encode($case_data)) . "\n"; $count = 1; } if ($count > 0) { list($ui, $suffix) = explode(".", $file); echo "测试用例 " . $ui . " ... 初始化成功,共" . $count . "个\n"; } } echo "初始化测试用例 ... 成功\n"; echo "...............................................................\n"; //初始化数据 $db = new db();
*/ require 'Predis/Autoloader.php'; Predis\Autoloader::register(); $REDIS_LIST_NAME = 'request'; //tries to decode JSON from the raw post data. If it can not, echos an error if ($content = json_decode(file_get_contents('php://input'), true)) { //varifies that the provided endpoint url is in valid form. Else echos an error if (filter_var($content['endpoint']['url'], FILTER_VALIDATE_URL)) { //varifies the endpoint method is supported. Else echos an error if (strtoupper($content['endpoint']['method']) == 'GET' || strtoupper($content['endpoint']['method']) == 'POST') { try { //makes a coonection to the local redis database $redis = new Predis\Client(); //makes separate "postback" objects for each received "data" object foreach ($content['data'] as $data) { $redis->rpush($REDIS_LIST_NAME, json_encode($content['endpoint'] + array('data' => $data))); } echo "Success!<br>"; } catch (Exception $e) { echo "Could not connect to Redis.<br>"; echo $e->getMessage(); } } else { echo 'Expected "method" to be GET or POST.<br>'; } } else { echo 'Expected valid "url".<br>'; } } else { echo 'Raw POST Request not in JSON form.<br>'; }
<?php require_once 'vendor/autoload.php'; require_once 'classes/service/StationBoardService.php'; require_once 'classes/converter/TrainServiceConverter.php'; $trainListService = new StationBoardService(); $converter = new TrainServiceConverter(); $redisClient = new Predis\Client(getenv('DB_PORT')); $targetStationCode = getenv('APP_STATION_CODE'); $departureBoard = $trainListService->getDepartingServices($targetStationCode, 20); if (is_null($departureBoard)) { echo "No Train departures from this station: " . $targetStationCode . "\n"; exit; } $listId = "dep-" . $departureBoard->station; $redisClient->del($listId); foreach ($departureBoard->nextDepartures as $trainService) { $redisClient->rpush($listId, $converter->toJson($trainService)); //echo $trainService . "\n"; }
<?php require_once 'vendor/autoload.php'; require_once 'classes/service/DisruptionService.php'; $disruptionService = new DisruptionService(); $redisClient = new Predis\Client(getenv('DB_PORT')); $targetStation = getenv('APP_STATION'); $disruption = $disruptionService->getDisruption(); $listId = "dis-" . $targetStation; $redisClient->del($listId); foreach ($disruption as $disruptionDetail) { $stoppingPoints = $disruptionDetail->stoppingPoints; if (in_array($targetStation, $stoppingPoints)) { $redisClient->rpush($listId, json_encode($disruptionDetail)); } //echo $disruptionDetail . "\n"; }
} if ($thisMethod == "GET") { foreach ($postData->data as &$dataItem) { $thisUrl = $host . '?'; $printedParameterCount = 0; foreach ($dataItemsTemplate as &$dataTemplate) { if (isset($dataItem->{$dataTemplate->value})) { if ($printedParameterCount++ > 0) { $thisUrl .= '&'; } $thisUrl .= $dataTemplate->key . '=' . $dataItem->{$dataTemplate->value}; } else { echo '<br />Notice: No Data For ' . $dataTemplate->key . '={' . $dataTemplate->value . '}'; } } echo "<br />Posting Data: {$thisUrl}"; $thisPush = array('method' => $thisMethod, 'url' => $thisUrl, 'R1' => $thisR1, 'stopwatch' => $stopwatch, 'S2' => round(microtime(true) * 1000)); if (isset($thisS1)) { $arrayS1 = array('S1' => $thisS1); $thisPush = array_merge($arrayS1, $thisPush); } $thisJSON = json_encode($thisPush); $redis->rpush("postbackQueue", $thisJSON); } } // else if( $thisMethod == "POST") { // $thisUrl = $thisStartUrl; // foreach($postData->{'data'} as &$dataItem) { // // } // }
<?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);
<?php // Mock server to pool requests and responses // Test cases add stub responses then rake actual requests // Use redis to communicate with the test require_once __DIR__ . '/../../vendor/autoload.php'; $errorResponseJson = '{"error":{"message":"Mock response is not prepared","type":"api_error","caused_by":"service"}}'; $client = new Predis\Client(); $request = array('method' => $_SERVER['REQUEST_METHOD'], 'request_uri' => $_SERVER['REQUEST_URI'], 'body' => file_get_contents("php://input")); $client->rpush('mdl_webpay_test_requests', serialize($request)); $head = $client->lpop('mdl_webpay_test_responses'); if ($head === NULL) { http_response_code(500); header('Content-Type: application/json'); print $errorResponseJson; } else { $response = unserialize($head); http_response_code($response['status_code']); header('Content-Type: application/json'); print $response['body']; }