function Redis_Connect($xmlFile) { if (!is_readable($xmlFile)) { throw new Exception(sprintf('File "%s" does not exits or is not readable.', $xmlFile)); } $xml = simplexml_load_file($xmlFile, 'SimpleXMLElement', LIBXML_NOCDATA); /** @noinspection PhpUndefinedFieldInspection */ $host = strval($xml->global->cache->backend_options->server); /** @noinspection PhpUndefinedFieldInspection */ $port = strval($xml->global->cache->backend_options->port); /** @noinspection PhpUndefinedFieldInspection */ $db = strval($xml->global->cache->backend_options->database); if (empty($host)) { throw new Exception(sprintf('Redis server hostname is not found in "%s".', $xmlFile)); } if (empty($port)) { throw new Exception(sprintf('Redis server port is not found in "%s".', $xmlFile)); } if (!strlen($db)) { throw new Exception(sprintf('Redis database number is not found in "%s".', $xmlFile)); } if ('/' == substr($host, 0, 1)) { // Socket $server = $host; } else { // TCP $server = sprintf('tcp://%s:%d', $host, $port); } $client = new Credis_Client($server); $client->select($db); return $client; }
protected function setUp() { $client = new \Credis_Client(self::REDIS_HOST, self::REDIS_PORT); $client->del('foo'); $client->del('key1'); $client->del('key2'); $this->keyValueStore = new CredisKeyValueStore($client); }
public function _load($session_id) { $host = (string) (Mage::getConfig()->getNode(self::XML_PATH_HOST) ?: '127.0.0.1'); $port = (int) (Mage::getConfig()->getNode(self::XML_PATH_PORT) ?: '6379'); $pass = (string) (Mage::getConfig()->getNode(self::XML_PATH_PASS) ?: ''); $timeout = (double) (Mage::getConfig()->getNode(self::XML_PATH_TIMEOUT) ?: '2.5'); $_redis = new Credis_Client($host, $port, $timeout); if (!empty($pass)) { $_redis->auth($pass); } $_redis->connect(); // connect to redis // replace sess_session_id with session id you want to read. $sessionData = $_redis->hGet('sess_' . $session_id, 'data'); // only data field is relevant to us, uncompress the data return $sessionData ? $this->_decodeData($sessionData) : false; }
public function testscan() { $this->credis->set('name', 'Jack'); $this->credis->set('age', '33'); $iterator = null; $result = $this->credis->scan($iterator, 'n*'); $this->assertEquals($iterator, 0); $this->assertEquals($result, ['name']); }
/** * 清楚redis中的所有缓存 */ public function flush() { if ($this->_prefix) { $keys = $this->_client->keys($this->_prefix); } else { $keys = $this->_client->keys("*"); } foreach ((array) $keys as $k) { $this->_client->del($k); } }
/** * @param string $id * @return array * @throws Exception */ public function _inspectSession($id) { if (!$this->_useRedis) { throw new Exception('Not connected to redis!'); } $sessionId = 'sess_' . $id; $this->_redis->select($this->_dbNum); $data = $this->_redis->hGetAll($sessionId); if ($data && isset($data['data'])) { $data['data'] = $this->_decodeData($data['data']); } return $data; }
public function testPubsub() { $timeout = 2; $time = time(); $this->credis->setReadTimeout($timeout); try { $testCase = $this; $this->credis->pSubscribe(array('foobar', 'test*'), function ($credis, $pattern, $channel, $message) use($testCase, &$time) { $time = time(); // Reset timeout // Test using: redis-cli publish foobar blah $testCase->assertEquals('blah', $message); }); $this->fail('pSubscribe should not return.'); } catch (CredisException $e) { $this->assertEquals($timeout, time() - $time); if ($this->useStandalone) { // phpredis does not distinguish between timed out and disconnected $this->assertEquals($e->getCode(), CredisException::CODE_TIMED_OUT); } else { $this->assertEquals($e->getCode(), CredisException::CODE_DISCONNECTED); } } // Perform a new subscription. Client should have either unsubscribed or disconnected $timeout = 2; $time = time(); $this->credis->setReadTimeout($timeout); try { $testCase = $this; $this->credis->subscribe('foobar', function ($credis, $channel, $message) use($testCase, &$time) { $time = time(); // Reset timeout // Test using: redis-cli publish foobar blah $testCase->assertEquals('blah', $message); }); $this->fail('subscribe should not return.'); } catch (CredisException $e) { $this->assertEquals($timeout, time() - $time); if ($this->useStandalone) { // phpredis does not distinguish between timed out and disconnected $this->assertEquals($e->getCode(), CredisException::CODE_TIMED_OUT); } else { $this->assertEquals($e->getCode(), CredisException::CODE_DISCONNECTED); } } }
/** * @param Credis_Client $masterClient * @param bool $writeOnly * @return Credis_Cluster */ public function setMasterClient(Credis_Client $masterClient, $writeOnly = false) { if (!$masterClient instanceof Credis_Client) { throw new CredisException('Master client should be an instance of Credis_Client'); } $this->masterClient = $masterClient; if (!isset($this->aliases['master'])) { $this->aliases['master'] = $masterClient; } if (!$writeOnly) { $this->clients[] = $this->masterClient; for ($replica = 0; $replica <= $this->replicas; $replica++) { $md5num = hexdec(substr(md5($this->masterClient->getHost() . ':' . $this->masterClient->getHost() . '-' . $replica), 0, 7)); $this->ring[$md5num] = count($this->clients) - 1; } $this->nodes = array_keys($this->ring); } return $this; }
/** * Log a hit or a miss to Redis. * * @param string $fullActionName * @param bool $hit */ public function logRequest($fullActionName, $hit) { try { $redis = new Credis_Client($this->config->server, NULL, 0.1); $redis->pipeline(); if ($this->config->db) { $redis->select($this->config->db); } $redis->incr('diehard:' . ($hit ? 'hit' : 'miss')); if ($fullActionName && $this->config->is('full_action_name')) { $redis->incr('diehard:' . $fullActionName . ':' . ($hit ? 'hit' : 'miss')); } $redis->exec(); $redis->close(); } catch (Exception $e) { Mage::log($e->getMessage(), Zend_Log::ERR, 'diehard_counter.log'); } }
/** * @return int */ public function getPort() { return $this->_client->getPort(); }
<?php $probe_file = "/fb_host_probe.txt"; class Mage { public static function throwException($msg) { die($msg); } } require "/credis.php"; $redis = new Credis_Client("clusterdata"); require "/varnish.php"; $varnish = new Nexcessnet_Turpentine_Model_Varnish_Admin_Socket(array("host" => "varnish", "auth_secret" => file_get_contents("/varnish.secret"))); // get first VCL (there should be always only one) $vcl = $varnish->vcl_list(); if ($vcl["code"] != Nexcessnet_Turpentine_Model_Varnish_Admin_Socket::CODE_OK) { die("Unable to read VCLs from Varnish"); } $vcl = explode("\n", trim($vcl["text"]))[0]; $vcl = explode(" ", $vcl); $vcl = $vcl[sizeof($vcl) - 1]; $vcl = $varnish->vcl_show($vcl); if ($vcl["code"] != Nexcessnet_Turpentine_Model_Varnish_Admin_Socket::CODE_OK) { die("Unable to read latest VCL from Varnish"); } $vcl = $vcl["text"]; $vcl = preg_replace("/#AUTOGENERATED_START.*#AUTOGENERATED_END/ms", "#AUTOGENERATED_START\n#AUTOGENERATED_END", $vcl); $vcl = explode("\n", $vcl); $apaches = array(); $hosts = array_keys($redis->hGetAll("fb_apache_containers"));
/** * Write session data to Redis * * @param $id * @param $data * @param $lifetime * @throws \Exception */ protected function _writeRawSession($id, $data, $lifetime) { $sessionId = 'sess_' . $id; $this->_redis->pipeline()->select($this->_dbNum)->hMSet($sessionId, array('data' => $this->_encodeData($data), 'lock' => 0))->hIncrBy($sessionId, 'writes', 1)->expire($sessionId, min($lifetime, $this->_maxLifetime))->exec(); }
#!/usr/bin/php <?php $config = ['git_urls' => ['https://github.com/colinmollenhour/credis.git' => 'credis/'], 'require_once' => ['credis/Client.php', 'credis/Cluster.php', 'credis/Sentinel.php'], 'example' => function () { $client = new Credis_Client(getenv('REDIS_HOST') ?: '127.0.0.1', 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);
<?php //version 0.0.1 $mageFilename = '../app/Mage.php'; require_once $mageFilename; Mage::setIsDeveloperMode(true); ini_set('display_errors', 1); umask(0); Mage::app(); /** * Set up the redis client */ $_redis; $_redis = new Credis_Client('localhost', 6379, 90, True); $_redis->select(0) || Zend_Cache::throwException('The redis database could not be selected.'); /** * Set up the Session Model to help with compression and other misc items. */ $session = Mage::getModel('Cm_RedisSession_Model_Session '); /** * Get the resource model */ $resource = Mage::getSingleton('core/resource'); /** * Retrieve the read connection */ $readConnection = $resource->getConnection('core_read'); // 1. query to order by session_expires, limit N, save last expire time, and session_id // 2. modify query with where session_expires >= last expire time, and session_id != session_id $exptime = 0; $lastid = 'NONE';
/** * Required to pass unit tests * * @param string $id * @return void */ public function ___expire($id) { $this->_redis->del(self::PREFIX_KEY . $id); }
/** * Get databases that exist in Redis instance * * @param Credis_Client|Redis $redis * @return array */ public static function getDatabases($redis) { return array_map(function ($db) { return (int) substr($db, 2); }, preg_grep("/^db[0-9]+\$/", array_keys($redis->info()))); }
/** * Perform an auto-failover which will re-elect another master and make the current master a slave * @param string $name * @return mixed */ public function failover($name) { return $this->_client->sentinel('failover', $name); }
public function testForceStandAloneAfterEstablishedConnection() { $this->credis->connect(); $this->setExpectedException('CredisException', 'Cannot force Credis_Client to use standalone PHP driver after a connection has already been established.'); $this->credis->forceStandalone(); }
public function testServer() { $this->assertArrayHasKey('used_memory', $this->credis->info()); $this->assertArrayHasKey('maxmemory', $this->credis->config('GET', 'maxmemory')); }
/** * {@inheritdoc} */ public function measure($variable, $value) { $this->credis_client->set($variable, $value); }
<?php //version 0.0.1 $mageFilename = '../app/Mage.php'; require_once $mageFilename; Mage::setIsDeveloperMode(true); ini_set('display_errors', 1); umask(0); Mage::app(); define('PREFIX', 'PHPREDIS_SESSION:'); /** * Set up the redis client */ $_redis; $_redis = new Credis_Client('localhost', 6379, 90, True); $_redis->select(0) || Zend_Cache::throwException('The redis database could not be selected.'); /** * Get the resource model */ $resource = Mage::getSingleton('core/resource'); /** * Retrieve the read connection */ $readConnection = $resource->getConnection('core_read'); // 1. query to order by session_expires, limit N, save last expire time, and session_id // 2. modify query with where session_expires >= last expire time, and session_id != session_id $exptime = 0; $lastid = 'NONE'; $batchlimit = 100; do { //$query = 'SELECT session_id, session_expires, session_data FROM ' . $resource->getTableName('core/session').
$user = json_decode($redis->get($key), true); if (empty($user)) { return 'Invalid user.'; } return 'Welcome ' . json_encode($user); }); $app->get('/auth/callback', function (Request $request) use($app) { $payload = array('client_id' => clientId(), 'client_secret' => clientSecret(), 'redirect_uri' => callbackUrl(), 'grant_type' => 'authorization_code', 'code' => $request->get('code'), 'scope' => $request->get('scope'), 'context' => $request->get('context')); $client = new Client(bcAuthService()); $req = $client->post('/oauth2/token', array(), $payload, array('exceptions' => false)); $resp = $req->send(); if ($resp->getStatusCode() == 200) { $data = $resp->json(); list($context, $storeHash) = explode('/', $data['context'], 2); $key = getUserKey($storeHash, $data['user']['email']); $redis = new Credis_Client('localhost'); $redis->set($key, json_encode($data['user'], true)); return 'Hello ' . json_encode($data); } else { return 'Something went wrong... [' . $resp->getStatusCode() . '] ' . $resp->getBody(); } }); function verifySignedRequest($signedRequest) { list($encodedData, $encodedSignature) = explode('.', $signedRequest, 2); // decode the data $signature = base64_decode($encodedSignature); $jsonStr = base64_decode($encodedData); $data = json_decode($jsonStr, true); // confirm the signature $expectedSignature = hash_hmac('sha256', $jsonStr, clientSecret(), $raw = false);
/** * Public for testing/inspection purposes only. * * @param $forceStandalone * @return \Credis_Client */ public function _redisClient($forceStandalone) { if ($forceStandalone) { $this->_redis->forceStandalone(); } if ($this->_dbNum) { $this->_redis->select($this->_dbNum); } return $this->_redis; }
public function testServer() { $this->assertTrue(array_key_exists('used_memory', $this->credis->info())); $this->assertTrue(array_key_exists('maxmemory', $this->credis->config('GET', 'maxmemory'))); }