/** * Отправляем метку количества не прочитанных сообщений * * @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()); }
/** * @param array $packet * @param array $options * * @return $this */ public function broadcast(array $packet, array $options) { // Encode to a string so that socket.io-redis can decode it. $data = $this->msgpack->encode([$packet, $options]); // Publish it on the channel. $this->predis->publish($this->channel, $data); // Allow chaining. return $this; }
/** * @param $eventName * @param $async * @param $serializedEvent */ private function redisPublish($eventName, $async, $serializedEvent) { if ($async) { $redisChannel = self::REDIS_CHANNEL . ':async:' . $eventName; } else { $redisChannel = self::REDIS_CHANNEL . ':sync:' . $eventName; } $this->redis->publish($redisChannel, $serializedEvent); }
public function ajaxPostChat(Request $request) { Predis\Autoloader::register(); try { $redis = new Client(); } catch (Exception $e) { die($e->getMessage()); } $redis->publish('chat-channel', json_encode($request->input('msg'))); return response()->json($request->input('msg')); }
/** * @group connected */ public function testDispatcherLoopAgainstRedisServerWithPrefix() { $parameters = array('host' => REDIS_SERVER_HOST, 'port' => REDIS_SERVER_PORT, 'database' => REDIS_SERVER_DBNUM, 'read_write_timeout' => 2); $options = array('profile' => REDIS_SERVER_VERSION); $producerNonPfx = new Client($parameters, $options); $producerNonPfx->connect(); $producerPfx = new Client($parameters, $options + array('prefix' => 'foobar')); $producerPfx->connect(); $consumer = new Client($parameters, $options + array('prefix' => 'foobar')); $dispatcher = new DispatcherLoop($consumer); $callback = $this->getMock('stdClass', array('__invoke')); $callback->expects($this->exactly(1))->method('__invoke')->with($this->equalTo('arg:prefixed'))->will($this->returnCallback(function ($arg) use($dispatcher) { $dispatcher->stop(); })); $dispatcher->attachCallback('callback', $callback); $producerNonPfx->publish('callback', 'arg:non-prefixed'); $producerPfx->publish('callback', 'arg:prefixed'); $dispatcher->run(); $this->assertTrue($consumer->ping()); }
public function emit() { $packet = ['type' => $this->type, 'data' => func_get_args(), 'nsp' => $this->namespace]; $options = ['rooms' => $this->rooms, 'flags' => $this->flags]; $channelName = sprintf('%s#%s#', $this->prefix, $packet['nsp']); $message = $this->packer->pack([$this->uid, $packet, $options]); // hack buffer extensions for msgpack with binary if ($this->type === Type::BINARY_EVENT) { $message = str_replace(pack('c', 0xda), pack('c', 0xd8), $message); $message = str_replace(pack('c', 0xdb), pack('c', 0xd9), $message); } // publish if (is_array($this->rooms) && count($this->rooms) > 0) { foreach ($this->rooms as $room) { $chnRoom = $channelName . $room . '#'; $this->client->publish($chnRoom, $message); } } else { $this->client->publish($channelName, $message); } // reset state return $this->reset(); }
/** * @group connected */ public function testPubSubAgainstRedisServer() { $parameters = array('host' => REDIS_SERVER_HOST, 'port' => REDIS_SERVER_PORT, 'database' => REDIS_SERVER_DBNUM, 'read_write_timeout' => 2); $options = array('profile' => REDIS_SERVER_VERSION); $messages = array(); $producer = new Client($parameters, $options); $producer->connect(); $consumer = new Client($parameters, $options); $consumer->connect(); $pubsub = new PubSubContext($consumer); $pubsub->subscribe('channel:foo'); $producer->publish('channel:foo', 'message1'); $producer->publish('channel:foo', 'message2'); $producer->publish('channel:foo', 'QUIT'); foreach ($pubsub as $message) { if ($message->kind !== 'message') { continue; } $messages[] = $payload = $message->payload; if ($payload === 'QUIT') { $pubsub->closeContext(); } } $this->assertSame(array('message1', 'message2', 'QUIT'), $messages); $this->assertFalse($pubsub->valid()); $this->assertTrue($consumer->ping()); }
/** * @group connected * @requires extension pcntl */ public function testPubSubAgainstRedisServerBlocking() { $parameters = array('host' => REDIS_SERVER_HOST, 'port' => REDIS_SERVER_PORT, 'database' => REDIS_SERVER_DBNUM, 'read_write_timeout' => -1); $options = array('profile' => REDIS_SERVER_VERSION); // create consumer before forking so the child can disconnect it $consumer = new Client($parameters, $options); $consumer->connect(); /* * fork * parent: consumer * child: producer */ if ($childPID = pcntl_fork()) { $messages = array(); $pubsub = new PubSubConsumer($consumer); $pubsub->subscribe('channel:foo'); foreach ($pubsub as $message) { if ($message->kind !== 'message') { continue; } $messages[] = $payload = $message->payload; if ($payload === 'QUIT') { $pubsub->stop(); } } $this->assertSame(array('message1', 'message2', 'QUIT'), $messages); $this->assertFalse($pubsub->valid()); $this->assertEquals('ECHO', $consumer->echo('ECHO')); // kill the child posix_kill($childPID, SIGKILL); } else { // create producer, read_write_timeout = 2 because it doesn't do blocking reads anyway $producer = new Client(array_replace($parameters, array('read_write_timeout' => 2)), $options); $producer->connect(); $producer->publish('channel:foo', 'message1'); $producer->publish('channel:foo', 'message2'); $producer->publish('channel:foo', 'QUIT'); // sleep, giving the consumer a chance to respond to the QUIT message sleep(1); // disconnect the consumer because otherwise it could remain stuck in blocking read // if it failed to respond to the QUIT message $consumer->disconnect(); // exit child exit(0); } }
$log = new Logger('serverlog'); $log->pushHandler(new StreamHandler(dirname(__DIR__) . '/' . $config['client']['log_file'])); //get params if (!$_REQUEST['sender'] || !$_REQUEST['receiver'] || !$_REQUEST['text']) { $log->error('Invalid request'); header("HTTP/1.1 420 OK"); die("ERR 110"); } $client = new PredisClient($config['redis_conn_url']); $bulkNum = (int) $client->get(BULK_COUNTER); $bulkNum++; $client->set(BULK_COUNTER, $bulkNum); $message = json_encode($_REQUEST); //store message $client->hset(BULK_HASH, $bulkNum, $message); $client->publish('bulkmocksend', $message); $client->quit(); $messageId = BulkUtils::guid(); $smsParts = BulkUtils::getNumberOfSMSsegments($_REQUEST['text']); ob_start(); //close http conn. and flush header("HTTP/1.1 202 OK"); echo "OK {$messageId} {$smsParts}"; $log->info("Valid request and replied: OK {$messageId} {$smsParts}"); header('Connection: close'); header('Content-Length: ' . ob_get_length()); ob_end_flush(); ob_flush(); flush(); //proceed with dlr if (!isset($_REQUEST['dlr-url'])) {
/** * @param InputInterface $input * @param OutputInterface $output * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $connection = $this->amqpApi->getConnection(TypeEnum::READ); $amqpHost = $connection->getHost(); $output->writeln('<info>Fetching events from ' . $amqpHost . '</info>'); } $startTime = $currentTick = time(); $hostname = gethostname(); $this->redis->publish('amqpfetcher:' . $hostname . ':start', $startTime); $queue = $this->amqpApi->getQueue(QueueEnum::VX_EVENTS); $context = ['CBASE_ENV' => getenv('CBASE_ENV')]; $isRunningTimeGood = true; $maxMemUsage = 1024 * 1024 * self::MAX_MEM_USAGE; try { $this->tracker->track(self::TRACKER_PREFIX . 'start', $context); $objectMapper = new ObjectMapper(); while ($isRunningTimeGood) { $now = time(); if ($currentTick !== $now && $now % self::HEARTBEAT === 0) { $this->redis->publish('amqpfetcher:' . $hostname . ':heartbeat', $now); $currentTick = $now; } $envelope = $queue->get(AMQP_AUTOACK); if ($envelope) { try { $this->redis->publish('amqpfetcher:input:' . $envelope->getRoutingKey(), $envelope->getBody()); $incomingAMQPEvent = $objectMapper->createIncomingAMQPEventFromAMQPEnvelope($envelope); $eventType = $incomingAMQPEvent->getEventType(); $mappingClass = IncomingAMQPEventsEnum::getEventMapping($eventType); $eventName = IncomingAMQPEventsEnum::getEventName($eventType); if ($eventName) { $event = $objectMapper->mapAMQPEnvelopeToEvent($incomingAMQPEvent, $mappingClass); $this->eventApi->dispatch($eventName, $event); $this->redis->publish('events:amqp:' . $eventName, json_encode($incomingAMQPEvent)); if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $output->writeln('<info>Event type ' . $eventType . ' dispatched as ' . $eventName . ', ' . $mappingClass . '</info>'); } } else { if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { $output->writeln('<comment>Event type ' . $eventType . ' will not be dispatched</comment>'); } } } catch (Exception $e) { $this->tracker->track(self::TRACKER_PREFIX . 'fail', $context); $errorMsg = 'AMQP Fetcher: ' . get_class($e) . ' - ' . $e->getMessage(); $this->logger->error($errorMsg, ['file' => $e->getFile() . ':' . $e->getLine()]); if (OutputInterface::VERBOSITY_QUIET !== $output->getVerbosity()) { $output->writeln('<error>' . $errorMsg . ' on ' . $e->getFile() . ':' . $e->getLine() . '</error>'); } } } $isRunningTimeGood = $now - $startTime <= self::MAX_TIME_RUNNING; $currentMemUsage = memory_get_usage(true); if ($currentMemUsage > $maxMemUsage) { throw new MemoryUsageExeededException($maxMemUsage, $currentMemUsage); } } $this->tracker->track(self::TRACKER_PREFIX . 'end', $context); } catch (MemoryUsageExeededException $e) { $this->logger->warning($e->getMessage(), $e->getContext()); $this->tracker->track(self::TRACKER_PREFIX . 'end', $context); if (OutputInterface::VERBOSITY_QUIET !== $output->getVerbosity()) { $output->writeln('<comment>' . $e->getMessage() . '</comment>'); } } catch (Exception $e) { $this->tracker->track(self::TRACKER_PREFIX . 'fail', $context); $errorMsg = 'AMQP Fetcher: ' . get_class($e) . ' - ' . $e->getMessage(); $this->logger->error($errorMsg, ['file' => $e->getFile() . ':' . $e->getLine()]); if (OutputInterface::VERBOSITY_QUIET !== $output->getVerbosity()) { $output->writeln('<error>' . $errorMsg . ' on ' . $e->getFile() . ':' . $e->getLine() . '</error>'); } } $this->redis->publish('amqpfetcher:' . $hostname . ':end', time()); return null; }
<error_code>' . $errorCode . '</error_code> <error_desc>' . htmlspecialchars($errorMap[$errorCode]) . '</error_desc> </report>'; exit; } ob_start(); $client = new PredisClient($config['redis_conn_url']); $mtNum = (int) $client->get('mt_num'); $mtNum++; $client->set('mt_num', $mtNum); //encode utf-8 $encRequest = array(); foreach ($_REQUEST as $key => $value) { $encRequest[$key] = utf8_encode($value); } $client->publish('premiummockmt', json_encode($encRequest)); $client->quit(); echo '<?xml version="1.0"?> <report> <status>success</status> <msg_id>' . $mtNum . '</msg_id> </report>'; //close http conn. and flush header('Connection: close'); header('Content-Length: ' . ob_get_length()); ob_end_flush(); ob_flush(); flush(); //sleep a while and then send DLR as per: //https://www.horisen.com/en/help/api-manuals/premium-transit#Delivery-Reports if (!isset($config['mt']['dlr_url'])) {
/** * Uses Redis PubSub implementation to push messages to the channel specified. * * @param string $channel * @param string $message * @return int */ public function publishMessage($channel, $message) { return $this->client->publish(sprintf('%s-%s', $this->pubsub_channel_prefix, $channel), base64_encode($message)); }