Author: Daniele Alessandri (suppakilla@gmail.com)
Inheritance: implements predis\ClientInterface
Example #1
1
 /**
  * {@inheritdoc}
  */
 public function save()
 {
     $contents = $this->getForStorage();
     $this->client->set($this->key, $contents);
     if ($this->expire !== null) {
         $this->client->expire($this->key, $this->expire);
     }
 }
Example #2
0
File: Request.php Project: eher/ldd
 public function save($client = null)
 {
     if ($client == null) {
         $client = new PredisClient();
     }
     $client->set($this->getId(), $this->toJson());
 }
Example #3
0
 /**
  * function that takes all keys from source redis, dumps them and imports to the new redis
  */
 public function copy()
 {
     // retrieve all keys from source redis
     $keys = $this->source->keys('*');
     $this->out("Processing %d REDIS keys ...", count($keys), true);
     $hundred = 0;
     $step = 0;
     foreach ($keys as $key) {
         // check for ignored keys and skip the key if it should be ignored
         foreach ($this->ignoredPrefixes as $ignoredPrefix) {
             if (strpos($key, $ignoredPrefix) !== false) {
                 $this->out('.');
                 continue 2;
                 // continue with the next key
             }
         }
         try {
             $ttl = max(0, (int) $this->source->ttl($key));
             $serializedValue = $this->source->dump($key);
             $this->destination->restore($key, $ttl, $serializedValue);
         } catch (Exception $e) {
             $this->out(PHP_EOL . 'ERROR: ' . $key . PHP_EOL);
         }
         if ($step++ % 100 == 0) {
             $this->out(PHP_EOL . $hundred++ . ': ');
         }
         $this->out('o');
     }
     $this->out(PHP_EOL . PHP_EOL);
 }
 public function testHandleLogWithGoodMessageNotImplementingJobInterface()
 {
     $worker = new WorkerPresence();
     $worker->setMemory(12345);
     $frame = new Frame('MESSAGE', array('delivery_tag' => 'delivery-' . mt_rand()), $worker->toJson());
     $loop = LoopFactory::create();
     $options = array('eventloop' => $loop, 'on_error' => array($this, 'throwRedisError'));
     $redisSync = new PredisSync('tcp://127.0.0.1:6379');
     $redisSync->connect();
     $resolver = $this->getResolver();
     $resolver->expects($this->once())->method('ack');
     $done = false;
     $phpunit = $this;
     $redis = new PredisAsync('tcp://127.0.0.1:6379', $options);
     $redis->connect(function () use($resolver, $phpunit, $redis, $frame, $redisSync, &$done, $worker) {
         $component = new LogBuilderComponent();
         $component->handleLog($redis, $phpunit->getLogger(), $frame, $resolver)->then(function ($hashId) use($phpunit, $redis, $redisSync, &$done, $worker) {
             $redis->disconnect();
             $phpunit->assertEquals($worker->toJson(), $redisSync->get($hashId));
             $phpunit->assertTrue($redisSync->sismember('garbages', $hashId));
             $done = true;
         });
     });
     $loop->run();
     $this->assertTrue($done);
 }
Example #5
0
 public function expireIn($key, $seconds)
 {
     $redisTime = $this->client->time();
     $at = ceil($redisTime[0] + $seconds);
     $this->client->expireat($this->prefixTimestamp($key), $at);
     return (int) $this->client->expireat($this->prefixKey($key), $at) === 1;
 }
Example #6
0
 /**
  * @inheritdoc
  */
 public function execute(CommandInterface $command)
 {
     if (!$this->isConnected()) {
         throw new ConnectionException('No connection established');
     }
     return $this->client->executeRaw(array_merge([$command->getCommand()], $command->getArguments()));
 }
Example #7
0
 /**
  * Отправляем метку количества не прочитанных сообщений
  *
  * @param int $user
  *
  * @return integer
  */
 protected function sendCountNotReadMessage($user)
 {
     $notReadMessage = $this->em->getRepository("UserMessagesBundle:Dialog")->findOneByNotReadMessage($user);
     if ($notReadMessage > 0) {
         $this->redis->publish('not-read', json_encode(['username' => 'username_' . $user, 'count' => $notReadMessage]));
     }
 }
 /**
  * @group connected
  */
 public function testDispatcherLoopAgainstRedisServer()
 {
     $parameters = array('host' => REDIS_SERVER_HOST, 'port' => REDIS_SERVER_PORT, 'database' => REDIS_SERVER_DBNUM, 'read_write_timeout' => 2);
     $producer = new Client($parameters, REDIS_SERVER_VERSION);
     $producer->connect();
     $consumer = new Client($parameters, REDIS_SERVER_VERSION);
     $consumer->connect();
     $dispatcher = new DispatcherLoop($consumer);
     $function01 = $this->getMock('stdClass', array('__invoke'));
     $function01->expects($this->exactly(2))->method('__invoke')->with($this->logicalOr($this->equalTo('01:argument'), $this->equalTo('01:quit')))->will($this->returnCallback(function ($arg) use($dispatcher) {
         if ($arg === '01:quit') {
             $dispatcher->stop();
         }
     }));
     $function02 = $this->getMock('stdClass', array('__invoke'));
     $function02->expects($this->once())->method('__invoke')->with('02:argument');
     $function03 = $this->getMock('stdClass', array('__invoke'));
     $function03->expects($this->never())->method('__invoke');
     $dispatcher->attachCallback('function:01', $function01);
     $dispatcher->attachCallback('function:02', $function02);
     $dispatcher->attachCallback('function:03', $function03);
     $producer->publish('function:01', '01:argument');
     $producer->publish('function:02', '02:argument');
     $producer->publish('function:01', '01:quit');
     $dispatcher->run();
     $this->assertTrue($consumer->ping());
 }
Example #9
0
 public function sort($tid, Request $request)
 {
     $sorts = BiliBiliHelper::getSorts();
     //分类非法检测
     if (!array_has($sorts, $tid)) {
         return $this->returnError('分类不存在');
     }
     $order = $request->get('order', 'hot');
     $page = $request->get('page', 1);
     //页码非法检测
     if ($page < 1) {
         $page = 1;
     }
     //默认取出redis
     if ($order == 'hot' && $page == 1) {
         $redis = new Client();
         $date = $redis->hget('update', 'sort');
         $sort = $redis->hget('sort', $sorts[$tid]);
         $sort = json_decode($sort, true);
     } else {
         try {
             $request_array = ['tid' => $tid, 'order' => $order, 'page' => $page, 'pagesize' => 20];
             $date = date('H:i:s');
             $back = RequestUtil::getUrl(BiliBiliHelper::$SERVICE_URL . '/sort?' . http_build_query($request_array));
             $sort = $back['content'];
         } catch (\Exception $e) {
             return $this->returnError('服务器君忙,待会再试吧...');
         }
     }
     return view('sort')->with('content', $sort)->with('tid', $tid)->with('page', $page)->with('date', $date);
 }
Example #10
0
 /**
  * Lazy connection
  *
  * Get the connection to Redis server and return it
  *
  * @throws \Predis\Connection\ConnectionException
  */
 public function getRedisClient()
 {
     if (empty($this->redisHandler)) {
         $this->redisHandler = new RedisHandler();
     }
     return $this->redisHandler->getConnection();
 }
    protected function getParametersAndOptions(Client $client)
    {
        $parameters = $client->getConnection()->getParameters();
        $options = $client->getOptions();

        return array($parameters, $options);
    }
Example #12
0
 public function returnMessage(QueueMessage $message)
 {
     // re-add the message to the queue, as the first element
     $this->predis->lpush($message->getQueueId(), $message->getMessage());
     // forget we received the message
     $this->completeMessage($message);
 }
 /**
  * @return string
  */
 public function createEvalShaKey()
 {
     $code = file_get_contents($this->getPathToLuaDir() . self::SOURCE_CODE_FILENAME);
     $sha = $this->redis->script('LOAD', $code);
     file_put_contents($this->getPathToLuaDir() . self::EVAL_SHA_FILENAME, $sha);
     return $sha;
 }
Example #14
0
 /**
  * @param string $queue Name of the queue to receive the job
  * @param string $command FQCN for Command class to be executed by the job
  * @param array $options Options for the Command class instance
  */
 public function publish($queue, $command, array $options = [])
 {
     if (!is_subclass_of($command, CommandInterface::class)) {
         throw new \RuntimeException('Class does not implement CommandInterface: ' . $command);
     }
     $job = json_encode(['command' => $command, 'options' => $options]);
     $this->client->rpush($queue, $job);
 }
Example #15
0
 /**
  * @return array
  * @throws UnavailableException
  */
 public function all()
 {
     try {
         return $this->client->keys('*');
     } catch (ServerException $ex) {
         throw new UnavailableException($ex->getMessage());
     }
 }
Example #16
0
 /**
  * @param int $userId
  * @return UserVO
  * @throws UserNotFoundException
  */
 public function loadUserById(int $userId) : UserVO
 {
     $redisUser = $this->redis->hgetall($this->getKey($userId));
     if (empty($redisUser)) {
         throw new UserNotFoundException(sprintf('User "%d" does not exist.', $userId));
     }
     return $this->buildUserVO($userId, $redisUser);
 }
Example #17
0
 /**
  * @param string $sessionId
  * @return array
  */
 public function getUserInfo($sessionId)
 {
     $userInfo = $this->redis->hgetall('session_' . $sessionId);
     if (!$userInfo) {
         throw new \RuntimeException('Session not found');
     }
     return $userInfo;
 }
 /**
  * Returns a new client instance.
  *
  * @return Client
  */
 protected function getClient()
 {
     $parameters = array('host' => REDIS_SERVER_HOST, 'port' => REDIS_SERVER_PORT, 'iterable_multibulk' => true, 'read_write_timeout' => 2);
     $client = new Client($parameters, REDIS_SERVER_VERSION);
     $client->connect();
     $client->select(REDIS_SERVER_DBNUM);
     $client->flushdb();
     return $client;
 }
Example #19
0
 /**
  * {@inheritdoc}
  */
 public function getUpdatedAt()
 {
     if ($this->client->exists('migraine:date')) {
         $date = new \DateTime();
         $date->setTimestamp(intval($this->client->get('migraine:date')));
         return $date;
     }
     return null;
 }
Example #20
0
 /**
  * {@inheritdoc}
  */
 protected function doGetStats()
 {
     $stats = $this->redis->info();
     $statsHits = isset($stats['keyspace_hits']) ? $stats['keyspace_hits'] : $stats['Stats']['keyspace_hits'];
     $statsMisses = isset($stats['keyspace_misses']) ? $stats['keyspace_misses'] : $stats['Stats']['keyspace_misses'];
     $statsMemoryUsage = isset($stats['used_memory']) ? $stats['used_memory'] : $stats['Memory']['used_memory'];
     $statsUptime = isset($stats['uptime_in_seconds']) ? $stats['uptime_in_seconds'] : $stats['Server']['uptime_in_seconds'];
     return array(Cache::STATS_HITS => $statsHits, Cache::STATS_MISSES => $statsMisses, Cache::STATS_UPTIME => $statsUptime, Cache::STATS_MEMORY_USAGE => $statsMemoryUsage, Cache::STATS_MEMORY_AVAILIABLE => null);
 }
 private function flushRedisCache($pattern)
 {
     $config = config('database.redis.' . config('cache.stores.redis.connection'));
     $client = new Redis(['scheme' => 'tcp', 'host' => $config['host'], 'port' => $config['port'], 'parameters' => ['password' => $config['password'], 'database' => $config['database']]]);
     $keys = $client->keys('collejo:criteria:' . str_replace('\\', '\\\\', $pattern) . ':*');
     foreach ($keys as $key) {
         $client->del($key);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function close()
 {
     $buffer =& $this->buffer;
     $this->redis->multiExec(function ($multi) use($buffer) {
         foreach ($buffer as $record) {
             $multi->rpush('monolog', $record);
         }
     });
 }
Example #23
0
 /**
  * @param $jobId
  *
  * @return AbstractJob
  */
 public function find($jobId)
 {
     $data = $this->redis->get($this->namespace . $jobId);
     $data = json_decode($data, true);
     $jobClass = $data[AbstractJob::P_JOB_CLASS];
     /** @var AbstractJob $job */
     $job = new $jobClass($data);
     return $job;
 }
 /**
  * @return void
  */
 private function checkReadFromStorage()
 {
     try {
         $this->client->get(self::KEY_HEARTBEAT);
     } catch (\Exception $e) {
         $this->addDysfunction(self::HEALTH_MESSAGE_UNABLE_TO_READ_FROM_STORAGE);
         $this->addDysfunction($e->getMessage());
     }
 }
 private function zSetPull($from = '')
 {
     if (empty($from)) {
         $from = '-inf';
     }
     $result = $this->client->zrangebyscore($this->key_header, $from, '+inf');
     //$this->client->zremrangebyscore($this->key_header, '-inf', strtotime("-1 mins"));
     return $result;
 }
 /**
  * @param Request $request
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function indexAction(Request $request)
 {
     $certificationCounter = [];
     foreach ($this->certificationManager->getCertifications() as $cn => $label) {
         $certificationCounter[$cn] = ['metrics' => (int) $this->redisClient->get($cn), 'label' => $label, 'icon' => $this->certificationManager->getContext($cn)->getIcons()];
     }
     $response = $this->engine->renderResponse('@CertificationyWeb/Site/homepage.html.twig', ['count_members' => (int) $this->userRepository->countMembers(), 'certification_done' => (int) $this->redisClient->get('total'), 'certification_counters' => $certificationCounter]);
     return $response;
 }
 public function fork()
 {
     $id = pcntl_fork();
     if (!$id) {
         $this->redis->disconnect();
         $this->redis->connect();
     }
     return $id;
 }
 public function countUsersOnline($pageKey)
 {
     $keys = [];
     $thisMinute = floor(time() / 60) * 60;
     for ($i = $thisMinute - 60 * self::ONLINE_MINUTES; $i <= $thisMinute; $i += 60) {
         $keys[] = $this->makeUsersOnlineKey($pageKey, $i);
     }
     return $this->redis->sunionstore(self::USERS_ONLINE_PREFIX, $keys);
 }
Example #29
0
 /**
  * Perform the check
  *
  * @see \ZendDiagnostics\Check\CheckInterface::check()
  * @return Failure|Success
  */
 public function check()
 {
     if (!class_exists('Predis\\Client')) {
         return new Failure('Predis is not installed');
     }
     $client = new Client(array('host' => $this->host, 'port' => $this->port));
     $client->ping();
     return new Success();
 }
 /**
  * {@inheritDoc}
  */
 public function count(array $sources)
 {
     call_user_func_array([$this->redis, 'zunionstore'], array_merge([$key = sha1(microtime()), count($sources)], array_map(function ($source) {
         return "aggregator:sources:{$source}";
     }, $sources)));
     $count = $this->redis->zcard($key);
     $this->redis->del($key);
     return $count;
 }