Can return response from REDIS subscribe?

Viewed 1482

I use predis and i want subscribe to channel in PHP and wait 30 seconds. If not receive any messages at channel, return json response. Or if messages in channel exists, return response too and exit.

For example i want, that my Redis::subscribe return $message and i can return response.

I have a some code in Controller in Laravel:

 Redis::subscribe(['PushAuthChanel'], function($message) {


  echo $message; // Nothing happens
  return response()->json($c, 200); // Nothing happens
  //return $message; // Nothing happens too

    });

And why Redis::subscribe can not return $message? But it well return exit code like this:

Redis::subscribe(['PushAuthChanel'], function($message) {


return exit(0); //will work
dd($message); //will work fine

});
2 Answers

I had similar issue, and resolved it by:

Connection to redis, I set 'read_timeout' => 30, it throws RedisException on read (subscribe) timeout, so we can catch that

try {
    Redis::subscribe(['channel-name'], function ($message) {
        die($message);
    });
} catch (\RedisException $exception) {
    return \Response::json([
        'timeout' => true
    ], 204);
}

On timeout, code response 204 (no content), so in this case client make immediately connect again (something as long polling connection)

Related