amphp / redis

Efficient asynchronous communication with Redis servers, enabling scalable and responsive data storage and retrieval.

Home Page:https://amphp.org/redis

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

example for pubsub?

fayland opened this issue · comments

anything wrong? I'm new to amphp

use Amp\Redis\Config;
use Amp\Redis\Redis;
use Amp\Redis\RemoteExecutor;
use Amp\Iterator;
use Amp\Delayed;
use Revolt\EventLoop;
use Amp\Redis\Subscriber;
use Amp\Redis\RedisException;
use Amp\Redis\Subscription;
use Amp\Socket\Socket;

Revolt\EventLoop::run(function () {
    $redisClient = new Subscriber(Config::fromUri('tcp://localhost:6379'));
    do {
        try {
            /** @var Subscription $subscription */
            $subscription = yield $redisClient->subscribe('channel');
            while (yield $subscription->advance()) {
                $message = $subscription->getCurrent();
                print_r($message);
            }
        } catch (RedisException $e) {
            yield new Delayed(1000);
        }
    } while (true);
});

it exited immediately.

Thanks

It seems you somehow mixed Amp v2 and v3. With Revolt / Amp v3, you don't need to explicitly run the event loop or use yield. I've added an example in 32350df now.

it seems blocking. can we have a non-blocking example?

foreach ($subscription as $message) {
    echo "Got " . $message . " on " . date('Y-m-d H:i:s') . "\n";
    __handle($message);
}

function __handle($msg) {
    sleep(30);
    return;
}

can use function Amp\ParallelFunctions\parallelMap;?
basically we want to process the message as fast as possible.

Thanks

It is non-blocking using Fibers, otherwise the example would block at the foreach and never run the async block. delay() is the non-blocking sleep equivalent.