Search code examples
laravelredispredis

Can't publish because predis is in subscriber mode (Laravel)


I have a command class called RedisSubscribe.php in Laravel 5.7. I want to be able to subscribe to 'message-channel', do some stuff with the message and then publish the message using redis to 'test-channel'. Everything is fine until I have to publish to the test channel. Redis of course can only either subscribe or publish, not do both, and I get this error message as a result: "ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / PING / QUIT allowed in this context".

So I know in node.js you can easily do this by creating two separate instances of ioredis by using the following code

var Redis = require('ioredis');
var subscriber = new Redis();
var publisher = new Redis();

How do I do something equivalent in PHP?

My code currently looks like this

public function handle()
    {
        Redis::subscribe(['message-channel'], function ($message){
            Redis::connection('my-connection');
            Redis::publish('test-channel', $message);
        });
    }
}

Apparently, I'm not using Redis::connection correctly because I still get the same error message.

'my-connection' in the database file looks like this:

'my-connection' => [
    'host' => env('REDIS_HOST', '127.0.0.1'),
    'password' => env('REDIS_PASSWORD', null),
    'port' => env('REDIS_PORT', 6379),
    'database' => env('REDIS_DB', 0),
],

Solution

  • You can create another redis instance and publish a message in Laravel by using this code

    $redis = Redis::connection('my-connection');
    $redis->publish('example-channel', $data);