All the commands exposed by the client generally have the same signature as described by the Redis documentation, but some of them offer an additional and more friendly interface to ease programming which is described in the following list of methods:
Author: Daniele Alessandri (suppakilla@gmail.com)
示例#1
0
文件: Atomic.php 项目: nrk/predis
 /**
  * {@inheritdoc}
  */
 public function __construct(ClientInterface $client)
 {
     if (!$client->getCommandFactory()->supportsCommands(array('multi', 'exec', 'discard'))) {
         throw new ClientException("'MULTI', 'EXEC' and 'DISCARD' are not supported by the current command factory.");
     }
     parent::__construct($client);
 }
示例#2
0
 /**
  * {@inheritdoc}
  */
 public function __construct(ClientInterface $client)
 {
     if (!$client->getProfile()->supportsCommands(array('multi', 'exec', 'discard'))) {
         throw new ClientException("The current profile does not support 'MULTI', 'EXEC' and 'DISCARD'.");
     }
     parent::__construct($client);
 }
示例#3
0
 /**
  * Broadcast the given event.
  *
  * @param  array $channels
  * @param  string $event
  * @param  array $payload
  * @return void
  */
 public function broadcast(array $channels, $event, array $payload = [])
 {
     $socket = isset($payload['socket']) ? $payload['socket'] : null;
     $payload = json_encode(['event' => $event, 'data' => $payload, 'socket' => $socket]);
     foreach ($this->formatChannels($channels) as $channel) {
         $this->redis->publish($channel, $payload);
     }
 }
 /**
  * @inheritdoc
  */
 public function has(AggregateIdInterface $id, $version)
 {
     if (!$this->redis->hexists(static::KEY_NAMESPACE, (string) $id)) {
         return false;
     }
     $snapshot = $this->serializer->deserialize($this->redis->hget(static::KEY_NAMESPACE, (string) $id), 'array', 'json');
     return $snapshot['version'] === $version;
 }
 /**
  * Set the cache for a token.
  *
  * @param $key
  * @param string $value
  * @param null $expiration
  */
 protected function cacheSet($key, $value, $expiration = null)
 {
     $this->client->set($key, $value);
     if (!empty($expiration)) {
         $this->ttl = $expiration;
     }
     $this->client->expire($key, $this->ttl);
 }
 /**
  * Returns a pipeline executor depending on the kind of the underlying
  * connection and the passed options.
  *
  * @param  ClientInterface           $client Client instance used by the context.
  * @return PipelineExecutorInterface
  */
 protected function createExecutor(ClientInterface $client)
 {
     $options = $client->getOptions();
     if (isset($options->exceptions)) {
         return new StandardExecutor($options->exceptions);
     }
     return new StandardExecutor();
 }
示例#7
0
文件: Queue.php 项目: aerogram/redis
 /**
  *
  * @throws QueueIsDraining If the Queue is Drainable
  *
  * @param string $message
  * @param array $options Message options (override Queue options):
  *
  * @return string Unique ID along the queue
  */
 protected function doEnqueue($message, $options = [])
 {
     // Score has form <priority>.<timestamp>
     $score = isset($options['score']) ? $options['score'] : 0;
     if ($priority = $this->getOption('priority', false, $options)) {
         $score += $priority;
     }
     $this->redis->zAdd($this->queueKey, $score, $message);
 }
示例#8
0
 /**
  * Checks if the passed client instance satisfies the required conditions
  * needed to initialize a monitor consumer.
  *
  * @param ClientInterface $client Client instance used by the consumer.
  *
  * @throws NotSupportedException
  */
 private function assertClient(ClientInterface $client)
 {
     if ($client->getConnection() instanceof AggregateConnectionInterface) {
         throw new NotSupportedException('Cannot initialize a monitor consumer over aggregate connections.');
     }
     if ($client->getProfile()->supportsCommand('MONITOR') === false) {
         throw new NotSupportedException("The current profile does not support 'MONITOR'.");
     }
 }
示例#9
0
 /**
  * Checks if the passed client instance satisfies the required conditions
  * needed to initialize a monitor context.
  *
  * @param ClientInterface $client Client instance used by the context.
  */
 private function checkCapabilities(ClientInterface $client)
 {
     if ($client->getConnection() instanceof AggregatedConnectionInterface) {
         throw new NotSupportedException('Cannot initialize a monitor context when using aggregated connections');
     }
     if ($client->getProfile()->supportsCommand('monitor') === false) {
         throw new NotSupportedException('The current profile does not support the MONITOR command');
     }
 }
 /**
  * Checks if the passed client instance satisfies the required conditions
  * needed to initialize a Publish / Subscribe context.
  *
  * @param ClientInterface $client Client instance used by the context.
  */
 private function checkCapabilities(ClientInterface $client)
 {
     if ($client->getConnection() instanceof AggregatedConnectionInterface) {
         throw new NotSupportedException('Cannot initialize a PUB/SUB context when using aggregated connections');
     }
     $commands = array('publish', 'subscribe', 'unsubscribe', 'psubscribe', 'punsubscribe');
     if ($client->getProfile()->supportsCommands($commands) === false) {
         throw new NotSupportedException('The current profile does not support PUB/SUB related commands');
     }
 }
示例#11
0
文件: Consumer.php 项目: nrk/predis
 /**
  * Checks if the client instance satisfies the required conditions needed to
  * initialize a PUB/SUB consumer.
  *
  * @param ClientInterface $client Client instance used by the consumer.
  *
  * @throws NotSupportedException
  */
 private function checkCapabilities(ClientInterface $client)
 {
     if ($client->getConnection() instanceof AggregateConnectionInterface) {
         throw new NotSupportedException('Cannot initialize a PUB/SUB consumer over aggregate connections.');
     }
     $commands = array('publish', 'subscribe', 'unsubscribe', 'psubscribe', 'punsubscribe');
     if ($client->getCommandFactory()->supportsCommands($commands) === false) {
         throw new NotSupportedException('PUB/SUB commands are not supported by the current command factory.');
     }
 }
示例#12
0
 /**
  * Releases the lock, if it has not been released already
  */
 public function release()
 {
     if ($this->released) {
         return;
     }
     // Only release the lock if it hasn't expired
     if ($this->expire >= time()) {
         $this->redis->del($this->key);
     }
     $this->released = true;
 }
示例#13
0
 private function deleteGlob($pattern)
 {
     $keys = $this->client->keys($pattern);
     $options = $this->client->getOptions();
     if (isset($options->prefix)) {
         $length = strlen($options->prefix->getPrefix());
         $keys = array_map(function ($key) use($length) {
             return substr($key, $length);
         }, $keys);
     }
     if (count($keys) === 0) {
         return;
     }
     $this->client->del($keys);
 }
示例#14
0
 /**
  * Remove an ID from an index
  * @param  string $id
  * @param  string $index
  * @return void
  */
 protected function removeIndexId(string $id, string $index)
 {
     if ($this->redis->scard($index) == 1) {
         return $this->redis->del($index);
     }
     return $this->redis->srem($index, $id);
 }
示例#15
0
 /**
  * @return array
  */
 public function getPosts() : array
 {
     if ($this->redisClient !== null) {
         $posts = $this->redisClient->get('posts');
         if ($posts) {
             return json_decode($posts, true);
         }
     }
     $blog = $this->getBlogInfo();
     $posts = $this->thumblrClient->getBlogPosts($blog['name'], ['type' => 'text'])->posts;
     $posts = json_encode($posts, JSON_PRETTY_PRINT);
     if ($this->redisClient !== null) {
         $this->redisClient->set('posts', $posts);
         $this->redisClient->expireat('posts', time() + 3600);
     }
     return json_decode($posts, true);
 }
示例#16
0
 /**
  * Configures the transaction using the provided options.
  *
  * @param ClientInterface $client  Underlying client instance.
  * @param array           $options Array of options for the transaction.
  * */
 protected function configure(ClientInterface $client, array $options)
 {
     if (isset($options['exceptions'])) {
         $this->exceptions = (bool) $options['exceptions'];
     } else {
         $this->exceptions = $client->getOptions()->exceptions;
     }
     if (isset($options['cas'])) {
         $this->modeCAS = (bool) $options['cas'];
     }
     if (isset($options['watch']) && ($keys = $options['watch'])) {
         $this->watchKeys = $keys;
     }
     if (isset($options['retry'])) {
         $this->attempts = (int) $options['retry'];
     }
 }
示例#17
0
文件: Lock.php 项目: AltThree/Locker
 /**
  * Release the lock if we possess it.
  *
  * Returns true if we released the lock, and false if it was already
  * released.
  *
  * @return bool
  */
 public function release()
 {
     if (!$this->locked()) {
         return false;
     }
     $this->redis->del($this->name);
     $this->state = self::UNLOCKED;
     return true;
 }
 /**
  * @test
  */
 public function testSettingACustomExpiration()
 {
     $token = $this->tokenProvider->getAccessTokenByToken('nnch734d00sl2jdk');
     $serializedToken = serialize($token);
     $key = 'tokenProvider/token/key:nnch734d00sl2jdk';
     $this->tokenProviderCache->cacheSet($key, $serializedToken, 500);
     $ttl = $this->client->ttl($key);
     $this->assertEquals(500, $ttl);
 }
示例#19
0
文件: PredisTest.php 项目: gmo/cache
 /**
  * @group redis-lists
  */
 public function testListRightPopLeftPush()
 {
     $this->assertNull($this->client->rpoplpush('foo', 'bar'));
     $this->assertEquals(array(), $this->client->lrange('bar', 0, -1));
     $this->client->rpush('foo', 'A', 'B');
     $this->client->rpush('bar', 'C', 'D');
     $this->assertEquals('B', $this->client->rpoplpush('foo', 'bar'));
     $this->assertEquals(array('A'), $this->client->lrange('foo', 0, -1));
     $this->assertEquals(array('B', 'C', 'D'), $this->client->lrange('bar', 0, -1));
 }
示例#20
0
 /**
  * Delete all keys from the cache
  *
  * @param bool $check if true will check expiration, otherwise delete all
  * @return bool True if the cache was successfully cleared, false otherwise
  */
 public function clear($check)
 {
     if ($check) {
         return true;
     }
     $keys = $this->client->keys($this->_config['prefix'] . '*');
     foreach ($keys as $key) {
         $this->client->del($key);
     }
     return true;
 }
 /**
  * @inheritdoc
  */
 public function registerNonceAndTimestamp($nonce, $timestamp, ConsumerInterface $consumer)
 {
     if ($this->checkNonceAndTimestampUnicity($nonce, $timestamp, $consumer)) {
         $noncesRedisKey = $this->noncesRedisKey($consumer, $timestamp);
         $this->client->sadd($noncesRedisKey, [$nonce]);
         $this->client->expire($noncesRedisKey, $this->ttl);
         $timestampsKey = $this->timestampsKey($consumer);
         $this->client->zadd($timestampsKey, $timestamp, $timestamp);
         // While we're here, only keep the top 10 items.
         $sortedSet = $this->client->zrevrange($timestampsKey, 0, -1);
         if (is_array($sortedSet) && !empty($sortedSet)) {
             $lastTimestamp = $sortedSet[0];
             $this->client->zremrangebyscore($timestampsKey, 0, $lastTimestamp - 1);
         }
         return true;
     } else {
         return false;
     }
 }
 /**
  * @test
  */
 public function it_only_keeps_the_last_ten_timestamps_per_consumer()
 {
     $key = "timestamps/key:{$this->consumer->getConsumerKey()}";
     $this->nonceProvider->registerNonceAndTimestamp('wNcUhAXuMe', 500, $this->consumer);
     $this->nonceProvider->registerNonceAndTimestamp('dTAmpjPUbk', 600, $this->consumer);
     $this->nonceProvider->registerNonceAndTimestamp('blnDetYfmx', 700, $this->consumer);
     $this->nonceProvider->registerNonceAndTimestamp('SiakXrdbZv', 800, $this->consumer);
     $this->nonceProvider->registerNonceAndTimestamp('cduemCfTOQ', 900, $this->consumer);
     $this->nonceProvider->registerNonceAndTimestamp('MMoVLLMHOn', 1000, $this->consumer);
     $this->nonceProvider->registerNonceAndTimestamp('BGRvLDLmdz', 1100, $this->consumer);
     $this->nonceProvider->registerNonceAndTimestamp('jRQiFtutXj', 1200, $this->consumer);
     $this->nonceProvider->registerNonceAndTimestamp('RwwgRAOYlG', 1300, $this->consumer);
     $this->nonceProvider->registerNonceAndTimestamp('WTjPgqtpFM', 1400, $this->consumer);
     $this->nonceProvider->registerNonceAndTimestamp('EhnRTUPMaZ', 1500, $this->consumer);
     $this->nonceProvider->registerNonceAndTimestamp('RZiDsxDded', 1600, $this->consumer);
     $this->nonceProvider->registerNonceAndTimestamp('FiWVeIpbBm', 1700, $this->consumer);
     $count = count($this->client->zrange($key, 0, -1));
     $this->assertEquals(1, $count);
 }
示例#23
0
 /**
  * @param SessionInterface $session
  * @param Response $response
  */
 private function postRequestHandle(SessionInterface $session, Response $response)
 {
     if ($this->sessionIsPersistent($config = $this->manager->getSessionConfig())) {
         $id = $session->getId();
         $key = 'session:' . $id;
         $content = $session->all();
         unset($content['_token'], $content['flash']);
         $lastSeen = time();
         $content['last_seen'] = $lastSeen;
         $session->set('last_seen', $lastSeen);
         $value = Json::dump($content);
         $this->redis->watch($key);
         $this->redis->multi();
         $this->redis->set($key, $value);
         $this->redis->expire($key, $this->getSessionLifetimeInSeconds());
         $this->redis->exec();
         $cookie = new Cookie($this->key, $id, $this->getCookieExpirationDate(), $config['path'], $config['domain'], Arr::get($config, 'secure', false));
         $response->headers->setCookie($cookie);
     }
 }
示例#24
0
 protected function tearDown()
 {
     $this->redis->flushall();
 }
示例#25
0
 /**
  * @param ClientInterface $client Client instance used by the context.
  */
 public function __construct(ClientInterface $client)
 {
     $this->callbacks = array();
     $this->pubSubContext = $client->pubSub();
 }
示例#26
0
 /**
  * {@inheritdoc}
  */
 public function updateTimestamp($sessionId, $data)
 {
     $this->redis->expire($sessionId, $this->ttl);
 }
示例#27
0
 public function keepAlive(JobInterface $job)
 {
     // This command keeps Predis connection alive during long-running processing,
     // called in HandleQueueCommand.php
     $this->predis->ping();
 }
示例#28
0
 /**
  * Ensures that the client supports the specified Redis command required to
  * fetch elements from the server to perform the iteration.
  *
  * @param ClientInterface $client    Client connected to Redis.
  * @param string          $commandID Command ID.
  *
  * @throws NotSupportedException
  */
 protected function requiredCommand(ClientInterface $client, $commandID)
 {
     if (!$client->getProfile()->supportsCommand($commandID)) {
         throw new NotSupportedException("The current profile does not support '{$commandID}'.");
     }
 }
示例#29
0
 /**
  * Checks if the passed client instance satisfies the required conditions
  * needed to initialize a transaction context.
  *
  * @param ClientInterface $client Client instance used by the context.
  */
 private function checkCapabilities(ClientInterface $client)
 {
     if ($client->getConnection() instanceof AggregatedConnectionInterface) {
         throw new NotSupportedException('Cannot initialize a MULTI/EXEC context when using aggregated connections');
     }
     $profile = $client->getProfile();
     if ($profile->supportsCommands(array('multi', 'exec', 'discard')) === false) {
         throw new NotSupportedException('The current profile does not support MULTI, EXEC and DISCARD');
     }
     $this->canWatch = $profile->supportsCommands(array('watch', 'unwatch'));
 }
示例#30
0
 /**
  * {@inheritdoc}
  */
 protected function doGetStats()
 {
     $info = $this->client->info();
     return array(Cache::STATS_HITS => $info['Stats']['keyspace_hits'], Cache::STATS_MISSES => $info['Stats']['keyspace_misses'], Cache::STATS_UPTIME => $info['Server']['uptime_in_seconds'], Cache::STATS_MEMORY_USAGE => $info['Memory']['used_memory'], Cache::STATS_MEMORY_AVAILABLE => false);
 }