/** * Try to get an item, and if missed call the fallback method to produce the value and store it. * * @param string $key * @param callable $fallback * @param int|\DateInterval|\DateTime|callback $validity Number of seconds this is valid for (if int) * @return mixed */ function getWithFallback($key, callable $fallback, $validity = null) { $value = $this->connection->get($key); if (!$value && !$this->connection->exists($key)) { $value = $fallback(); if (is_callable($validity)) { $validity = call_user_func($validity, $value); } $this->set($key, $value, $validity); return $value; } return $value; }
public function testExists() { $key = 'key' . rand(); $this->assertFalse($this->redis->exists($key)); $this->redis->add($key, 'val'); $this->assertTrue($this->redis->exists($key)); }
public function exists($key) { if (!$this->isConnected()) { return false; } return (bool) $this->redis->exists($key); }
/** * @param $key * @return Option */ public static function getMy($key) { $hash = self::hash($key); if (self::$redis->exists(self::myPrefix() . ":" . $hash)) { return Option::Some(unserialize(self::$redis->get(self::myPrefix() . ":" . $hash))); } else { return Option::None(); } }
/** * Returns a list of all affected hashes for a given set of tags. * * @param array $tags * * @return array */ private function getHashes(array $tags) { $hashes = []; foreach ($tags as $tag) { $tag = $this->redis->prefix($tag); if (!$this->redis->exists($tag)) { continue; } $hashes = array_merge($hashes, $this->redis->smembers($tag)); } return array_unique($hashes); }
/** * Tells if this backend is frozen. * * @return boolean */ public function isFrozen() { if (null === $this->frozen) { $this->frozen = $this->redis->exists($this->buildKey('frozen')); } return $this->frozen; }
public function _display_cache(&$CFG, &$URI) { $cache_path = $CFG->item('cache_path') === '' ? APPPATH . 'cache/' : $CFG->item('cache_path'); $uri = $CFG->item('base_url') . $CFG->item('index_page') . $URI->uri_string; if ($CFG->item('cache_query_string') && !empty($_SERVER['QUERY_STRING'])) { $uri .= '?' . $_SERVER['QUERY_STRING']; } $filepath = $cache_path . md5($uri); $redis = new Redis(); $host = $CFG->item("redis_host"); $port = $CFG->item("redis_port"); $redis->connect($host, $port); if ($redis->exists($filepath)) { $cache = $redis->get($filepath); if (!preg_match('/^(.*)ENDCI--->/', $cache, $match)) { return false; } } else { return false; } $cache_info = unserialize($match[1]); $expire = $cache_info['expire']; $last_modified = $cache_info["last_modified"]; $this->set_cache_header($last_modified, $expire); foreach ($cache_info['headers'] as $header) { $this->set_header($header[0], $header[1]); } $this->_display(substr($cache, strlen($match[0]))); log_message('debug', 'Cache is current. Sending it to browser.'); return TRUE; }
/** * {@inheritDoc} */ public function removeWord($language, $word) { $word = mb_strtolower($word, mb_detect_encoding($word)); if ($this->redis->exists($word)) { $languages = unserialize($this->redis->get($word)); if (false !== ($index = array_search($language, $languages))) { unset($languages[$index]); if (!count($languages)) { $this->redis->del($word); } else { $this->redis->set($word, serialize($languages)); } } } return $this; }
public function testExists() { $this->redis->delete('key'); $this->assertFalse($this->redis->exists('key')); $this->redis->set('key', 'val'); $this->assertEquals(True, $this->redis->exists('key')); }
/** * @param string $digest * @param string $nonce * @param string $created * @param string $secret * * @return bool * @throws \Symfony\Component\Security\Core\Exception\NonceExpiredException */ protected function validateDigest($digest, $nonce, $created, $secret) { /* * закомментили 7.01.2014 из-за проблемы возможного расхождения с клиентским временем * // Check created time is not in the future if (strtotime($created) > time()) { return false; } // Expire timestamp after 5 minutes if (time() - strtotime($created) > self::TTL) { return false; } */ // Validate nonce is unique within 5 minutes if ($this->redis->exists(self::PREFIX . ':' . $nonce)) { if (null !== $this->logger) { $this->logger->debug(sprintf('Previously used nonce detected: %s', base64_decode($nonce))); } throw new NonceExpiredException('Previously used nonce detected'); } $this->redis->setex(self::PREFIX . ':' . $nonce, self::TTL, time()); // Validate Secret $expected = base64_encode(sha1(base64_decode($nonce) . $created . $secret, true)); if (null !== $this->logger) { $this->logger->debug(sprintf('[+] %s, [=] %s (created: %s, nonce: %s, secret: %s)', $digest, $expected, $created, base64_decode($nonce), $secret)); } return $digest === $expected; }
/** * key是否存在,存在返回ture * @param string $cache_id KEY名称 */ public function exists($cache_id) { try { return $this->_redis->exists($cache_id); } catch (Exception $e) { $this->_error = $e->getMessage(); return false; } }
/** * 摧毁SESSION * * @param int $id key * * @return bool true/false */ public function destroy($id) { $id = 'sess_' . $id; if ($this->redis->exists($id)) { return $this->redis->delete($id); } return true; }
/** * {@inheritDoc} */ public function find($storageName, $key) { $key = $this->getKeyName($key); if (!$this->client->exists($key)) { throw new NotFoundException(); } return json_decode($this->client->get($key), true); }
/** * Destroy a session. * Expects a session id. * @param string $sessionId * @return boolean */ public function destroy($sessionId = '') { if ($sessionId !== '' && $this->_redis->exists($this->_key($sessionId))) { $this->_redis->del($this->_key($sessionId)); } session_destroy(); return true; }
/** * Appends data to an existing item on the Redis server. * * @param string $key * @param string $value * @param int $expiration * @return bool */ protected function appendValue($key, $value, $expiration = 0) { if ($this->redis->exists($key)) { $this->redis->append($key, $value); return $this->redis->expire($key, $expiration); } return $this->redis->setex($key, $expiration, $value); }
public function populate() { $redis = new Redis(); $redis->connect('127.0.0.1', 6379); if (!$redis->exists('key')) { $redis->set('key', 'val'); } return $redis->get('key'); }
/** * 判断是否存在该k,注意在集群中,并不会查找全部集群,只查找当前指定的实例Id * @return bool 存在返回TRUE,否则返回FALSE */ public function exists() { try { return $this->rd->exists($this->k); } catch (\RedisException $e) { if ($this->reconnRedis()) { return $this->rd->exists($this->k); } } return FALSE; }
/** * @test Implementation */ public function collectGarbageRemovesLeftOverIdentifierToTagsSet() { $this->setUpBackend(); $this->setUpRedis(); $identifier = 'identifier' . uniqid(); $this->backend->set($identifier . 'A', 'data', array('tag')); $this->backend->set($identifier . 'B', 'data', array('tag')); $this->redis->delete('identData:' . $identifier . 'A'); $this->backend->collectGarbage(); $expectedResult = array(FALSE, TRUE); $actualResult = array($this->redis->exists('identTags:' . $identifier . 'A'), $this->redis->exists('identTags:' . $identifier . 'B')); $this->assertSame($expectedResult, $actualResult); }
/** * With the current internal structure, only the identifier to data entries * have a redis internal lifetime. If an entry expires, attached * identifier to tags and tag to identifiers entries will be left over. * This methods finds those entries and cleans them up. * * Scales O(n*m) with number of cache entries (n) and number of tags (m) * * @return void * @api */ public function collectGarbage() { $identifierToTagsKeys = $this->redis->getKeys(self::IDENTIFIER_TAGS_PREFIX . '*'); foreach ($identifierToTagsKeys as $identifierToTagsKey) { list(, $identifier) = explode(':', $identifierToTagsKey); // Check if the data entry still exists if (!$this->redis->exists(self::IDENTIFIER_DATA_PREFIX . $identifier)) { $tagsToRemoveIdentifierFrom = $this->redis->sMembers($identifierToTagsKey); $queue = $this->redis->multi(\Redis::PIPELINE); $queue->delete($identifierToTagsKey); foreach ($tagsToRemoveIdentifierFrom as $tag) { $queue->sRemove(self::TAG_IDENTIFIERS_PREFIX . $tag, $identifier); } $queue->exec(); } } }
public function replace($key, $data, $group = 'default', $expire = 0) { if (empty($group)) { $group = 'default'; } if ($this->_connected && !in_array($group, $this->_no_redis_groups)) { try { if ($this->_redis->exists($this->_get_redis_key($key, $group))) { return $this->set($key, $data, $group, $expire); } } catch (Exception $e) { $this->_connected = false; return false; } } elseif ($this->_exists($key, $group)) { return $this->set($key, $data, $group, $expire); } return false; }
* @author dzhua * @date 2015-10-23 */ //开启缓存:true, 关闭缓存:false $use_cache = true; $path = trim($_GET['path']); if ($use_cache) { $path = dirname(__FILE__) . trim($_GET['path']); if (file_exists($path)) { $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $redis->select(10); //断点续传206 http_response_code(206); header('Content-type: image/jpeg'); if ($redis->exists($path)) { echo $redis->get($path); } else { $img = file_get_contents($path); echo $img; $redis->set($path, $img); $redis->expire($path, 86400 * 30); } } else { /* $fileName = date('Y-m-d').'img.log'; $text = $path.PHP_EOF; if($fp = fopen($fileName, 'a')) { if(@fwrite($fp, $text)) { @fclose($fp); } else {
private function checkSerializer($mode) { $this->redis->delete('key'); $this->assertTrue($this->redis->getOption(Redis::OPT_SERIALIZER) === Redis::SERIALIZER_NONE); // default $this->assertTrue($this->redis->setOption(Redis::OPT_SERIALIZER, $mode) === TRUE); // set ok $this->assertTrue($this->redis->getOption(Redis::OPT_SERIALIZER) === $mode); // get ok // lPush, rPush $a = array('hello world', 42, TRUE, array('<tag>' => 1729)); $this->redis->delete('key'); $this->redis->lPush('key', $a[0]); $this->redis->rPush('key', $a[1]); $this->redis->rPush('key', $a[2]); $this->redis->rPush('key', $a[3]); // lGetRange $this->assertTrue($a === $this->redis->lGetRange('key', 0, -1)); // lGet $this->assertTrue($a[0] === $this->redis->lGet('key', 0)); $this->assertTrue($a[1] === $this->redis->lGet('key', 1)); $this->assertTrue($a[2] === $this->redis->lGet('key', 2)); $this->assertTrue($a[3] === $this->redis->lGet('key', 3)); // lRemove $this->assertTrue($this->redis->lRemove('key', $a[3]) === 1); $this->assertTrue(array_slice($a, 0, 3) === $this->redis->lGetRange('key', 0, -1)); // lSet $a[0] = array('k' => 'v'); // update $this->assertTrue(TRUE === $this->redis->lSet('key', 0, $a[0])); $this->assertTrue($a[0] === $this->redis->lGet('key', 0)); // lInsert $this->assertTrue($this->redis->lInsert('key', Redis::BEFORE, $a[0], array(1, 2, 3)) === 4); $this->assertTrue($this->redis->lInsert('key', Redis::AFTER, $a[0], array(4, 5, 6)) === 5); $a = array(array(1, 2, 3), $a[0], array(4, 5, 6), $a[1], $a[2]); $this->assertTrue($a === $this->redis->lGetRange('key', 0, -1)); // sAdd $this->redis->delete('key'); $s = array(1, 'a', array(1, 2, 3), array('k' => 'v')); $this->assertTrue(1 === $this->redis->sAdd('key', $s[0])); $this->assertTrue(1 === $this->redis->sAdd('key', $s[1])); $this->assertTrue(1 === $this->redis->sAdd('key', $s[2])); $this->assertTrue(1 === $this->redis->sAdd('key', $s[3])); // variadic sAdd $this->redis->delete('k'); $this->assertTrue(3 === $this->redis->sAdd('k', 'a', 'b', 'c')); $this->assertTrue(1 === $this->redis->sAdd('k', 'a', 'b', 'c', 'd')); // sRemove $this->assertTrue(1 === $this->redis->sRemove('key', $s[3])); $this->assertTrue(0 === $this->redis->sRemove('key', $s[3])); // variadic $this->redis->delete('k'); $this->redis->sAdd('k', 'a', 'b', 'c', 'd'); $this->assertTrue(2 === $this->redis->sRem('k', 'a', 'd')); $this->assertTrue(2 === $this->redis->sRem('k', 'b', 'c', 'e')); $this->assertTrue(FALSE === $this->redis->exists('k')); // sContains $this->assertTrue(TRUE === $this->redis->sContains('key', $s[0])); $this->assertTrue(TRUE === $this->redis->sContains('key', $s[1])); $this->assertTrue(TRUE === $this->redis->sContains('key', $s[2])); $this->assertTrue(FALSE === $this->redis->sContains('key', $s[3])); unset($s[3]); // sMove $this->redis->delete('tmp'); $this->redis->sMove('key', 'tmp', $s[0]); $this->assertTrue(FALSE === $this->redis->sContains('key', $s[0])); $this->assertTrue(TRUE === $this->redis->sContains('tmp', $s[0])); unset($s[0]); // sorted sets $z = array('z0', array('k' => 'v'), FALSE, NULL); $this->redis->delete('key'); // zAdd $this->assertTrue(1 === $this->redis->zAdd('key', 0, $z[0])); $this->assertTrue(1 === $this->redis->zAdd('key', 1, $z[1])); $this->assertTrue(1 === $this->redis->zAdd('key', 2, $z[2])); $this->assertTrue(1 === $this->redis->zAdd('key', 3, $z[3])); // zDelete $this->assertTrue(1 === $this->redis->zDelete('key', $z[3])); $this->assertTrue(0 === $this->redis->zDelete('key', $z[3])); unset($z[3]); // check that zDelete doesn't crash with a missing parameter (GitHub issue #102): $this->assertTrue(FALSE === @$this->redis->zDelete('key')); // variadic $this->redis->delete('k'); $this->redis->zAdd('k', 0, 'a'); $this->redis->zAdd('k', 1, 'b'); $this->redis->zAdd('k', 2, 'c'); $this->assertTrue(2 === $this->redis->zDelete('k', 'a', 'c')); $this->assertTrue(1.0 === $this->redis->zScore('k', 'b')); $this->assertTrue($this->redis->zRange('k', 0, -1, true) == array('b' => 1.0)); // zRange $this->assertTrue($z === $this->redis->zRange('key', 0, -1)); // zScore $this->assertTrue(0.0 === $this->redis->zScore('key', $z[0])); $this->assertTrue(1.0 === $this->redis->zScore('key', $z[1])); $this->assertTrue(2.0 === $this->redis->zScore('key', $z[2])); // zRank $this->assertTrue(0 === $this->redis->zRank('key', $z[0])); $this->assertTrue(1 === $this->redis->zRank('key', $z[1])); $this->assertTrue(2 === $this->redis->zRank('key', $z[2])); // zRevRank $this->assertTrue(2 === $this->redis->zRevRank('key', $z[0])); $this->assertTrue(1 === $this->redis->zRevRank('key', $z[1])); $this->assertTrue(0 === $this->redis->zRevRank('key', $z[2])); // zIncrBy $this->assertTrue(3.0 === $this->redis->zIncrBy('key', 1.0, $z[2])); $this->assertTrue(3.0 === $this->redis->zScore('key', $z[2])); $this->assertTrue(5.0 === $this->redis->zIncrBy('key', 2.0, $z[2])); $this->assertTrue(5.0 === $this->redis->zScore('key', $z[2])); $this->assertTrue(2.0 === $this->redis->zIncrBy('key', -3.0, $z[2])); $this->assertTrue(2.0 === $this->redis->zScore('key', $z[2])); // mset $a = array('k0' => 1, 'k1' => 42, 'k2' => NULL, 'k3' => FALSE, 'k4' => array('a' => 'b')); $this->assertTrue(TRUE === $this->redis->mset($a)); foreach ($a as $k => $v) { $this->assertTrue($this->redis->get($k) === $v); } $a = array('k0' => 1, 'k1' => 42, 'k2' => NULL, 'k3' => FALSE, 'k4' => array('a' => 'b')); // hSet $this->redis->delete('key'); foreach ($a as $k => $v) { $this->assertTrue(1 === $this->redis->hSet('key', $k, $v)); } // hGet foreach ($a as $k => $v) { $this->assertTrue($v === $this->redis->hGet('key', $k)); } // hGetAll $this->assertTrue($a === $this->redis->hGetAll('key')); $this->assertTrue(TRUE === $this->redis->hExists('key', 'k0')); $this->assertTrue(TRUE === $this->redis->hExists('key', 'k1')); $this->assertTrue(TRUE === $this->redis->hExists('key', 'k2')); $this->assertTrue(TRUE === $this->redis->hExists('key', 'k3')); $this->assertTrue(TRUE === $this->redis->hExists('key', 'k4')); // hMSet $this->redis->delete('key'); $this->redis->hMSet('key', $a); foreach ($a as $k => $v) { $this->assertTrue($v === $this->redis->hGet('key', $k)); } // hMget $hmget = $this->redis->hMget('key', array_keys($a)); foreach ($hmget as $k => $v) { $this->assertTrue($v === $a[$k]); } // getMultiple $this->redis->set('a', NULL); $this->redis->set('b', FALSE); $this->redis->set('c', 42); $this->redis->set('d', array('x' => 'y')); $this->assertTrue(array(NULL, FALSE, 42, array('x' => 'y')) === $this->redis->getMultiple(array('a', 'b', 'c', 'd'))); // pipeline $this->sequence(Redis::PIPELINE); // multi-exec $this->sequence(Redis::MULTI); // keys $this->assertTrue(is_array($this->redis->keys('*'))); // issue #62, hgetall $this->redis->del('hash1'); $this->redis->hSet('hash1', 'data', 'test 1'); $this->redis->hSet('hash1', 'session_id', 'test 2'); $data = $this->redis->hGetAll('hash1'); $this->assertTrue($data['data'] === 'test 1'); $this->assertTrue($data['session_id'] === 'test 2'); // issue #145, serializer with objects. $this->redis->set('x', array(new stdClass(), new stdClass())); $x = $this->redis->get('x'); $this->assertTrue(is_array($x)); $this->assertTrue(is_object($x[0]) && get_class($x[0]) === 'stdClass'); $this->assertTrue(is_object($x[1]) && get_class($x[1]) === 'stdClass'); // revert $this->assertTrue($this->redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE) === TRUE); // set ok $this->assertTrue($this->redis->getOption(Redis::OPT_SERIALIZER) === Redis::SERIALIZER_NONE); // get ok }
/** * Check if a key exists in the cache. * * @param string $key * * @return bool */ public function has($key) { return (bool) $this->redis->exists($this->redis->prefix($key)); }
<?php $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $mysql_conn = mysql_connect("localhost", "root", ''); if (!$mysql_conn) { die('connect fail ' . mysql_error()); } mysql_query("set character set 'utf8'"); mysql_select_db("thinkphp", $mysql_conn); //user表 $user_keys = $redis->keys('user*'); foreach ($user_keys as $key) { if ($redis->exists($key)) { $redis->delete($key); echo $key . " delete success" . PHP_EOL; } else { die('delete table user keys not exists'); } } // die(); $sql = 'select * from user'; $result = mysql_query($sql); while ($user_res = mysql_fetch_array($result)) { $redis->set('user:uid:username:'******'uid'], $user_res['username']); $redis->set('user:uid:password:'******'uid'], $user_res['password']); $redis->set('user:uid:mobile:' . $user_res['mobile'], $user_res['mobile']); echo 'user_res' . $user_res['uid'] . 'update success' . PHP_EOL; } mysql_free_result($result); echo "table user update success" . PHP_EOL;
/** * {@inheritdoc} */ protected function doContains($id) { return (bool) $this->redis->exists($id); }
$redis = new Redis(); $redis->connect('127.0.0.1'); // port 6379 by default } // Sometimes a layer doesn't refresh in openlayers, I noticed that the only difference is that the difference between a good // and a bad request is the header 'Vary: Accept-Encoding' // http://stackoverflow.com/questions/14540490/is-vary-accept-encoding-overkill // http://stackoverflow.com/questions/7848796/what-does-varyaccept-encoding-mean // $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); // use built-in serialize/unserialize if ($redis) { $redis->setOption(Redis::OPT_PREFIX, 'grb:'); // use custom prefix on all keys } $cachekey = md5($sql); if ($redis) { if ($redis->exists($cachekey)) { header("X-Redis-Cached: true"); $result = $redis->get($cachekey); $uncompressed = @gzuncompress($result); if ($uncompressed !== false) { echo $uncompressed; } else { echo $result; } exit; } } # Connect to PostgreSQL database $conn = pg_pconnect("dbname='grb' user='******' password='******' host='localhost'"); if (!$conn) { echo json_encode(pg_last_error());
/** * Decrement a raw value * * @param string $id Cache ID * @param int $offset Step/value to reduce by * @return mixed New value on success or FALSE on failure */ public function decrement($id, $offset = 1) { return $this->_redis->exists($id) ? $this->_redis->decr($id, $offset) : FALSE; }
public function exists($key) { return $this->connection->exists($key); }
<?php header("Content-Type: text/html;charset=utf-8"); $cookie = $_POST["Cookie"]; $redis = new Redis(); $redis->connect('127.0.0.1', 6379); if (strpos($cookie, "DedeUserID") === FALSE or strpos($cookie, "DedeUserID__ckMd5") === FALSE or strpos($cookie, "SESSDATA") === FALSE) { echo "<script>alert('Cookie数据不符合要求,请重试!');history.go(-1);</script>"; exit; } $keyname = preg_replace('{(.*)?DedeUserID=([\\d]+);(.*)?}', '$2', $cookie); if ($redis->exists($keyname)) { $status = $redis->hget($keyname, 'status'); $cookieexist = $redis->hget($keyname, 'cookie'); if ($status == 'processing') { echo "<script>alert('正在为你领取银瓜子~');history.go(-1);</script>"; exit; } elseif ($status == 'processed') { echo "<script>alert('今天的银瓜子已经领完了,明天再来吧~');history.go(-1);</script>"; exit; } elseif ($status == 'problem') { if ($cookieexist == $cookie) { echo "<script>alert('Cookie数据有问题,请尝试重新登录获取后再提交!');history.go(-1);</script>"; exit; } else { echo "<script>alert('成功更新Cookie数据!');</script>"; } } else { echo "<script>alert('你的任务正在队列中,稍后再看看吧~');history.go(-1);</script>"; exit; }
/** * @inheritdoc */ public function exist($key) { return $this->redis->exists($key); }