Bob Lee
Bob Lee

Reputation: 71

How do I subscribe using yii2 and redis?

I want to use a method in yii2 controller to subscribe to channel so that I can receive realtime update as a subscribed client. I am using redis pub/sub.

public function actionSubscribe(){
        Yii::$app->redis->executeCommand('SUBSCRIBE',
        ['notification'], 
        function($redis, $channel, $message){
                print('I just did it!!!!!!');               
        });
        return true;
}

I am also using nodeJs and below is my serverside nodeJs code. Please what am I doing wrong?

I extracted this section that refused to work from the code.

        socket.on("message", function(channel, message) {
        console.log("New message: " + message + ". In channel: " + channel);
        socket.emit(channel, message);
    });

BELOW IS THE FULL CODE

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');

server.listen(8890);

 io.on('connection', function (socket) {

    console.log("new client connected");

    var redisClient = redis.createClient();
    //RedisClient deliberately pegged because I want Yii2 php to do the 
    //subscription to the notification channel; not nodeJs.
    //redisClient.subscribe('notification');

    socket.on("message", function(channel, message) {
        console.log("New message: " + message + ". In channel: " + channel);
        socket.emit(channel, message);
    });

    socket.on('disconnect', function() {
       // redisClient.quit();
    });

}) ;

Upvotes: 1

Views: 1220

Answers (1)

Pritish Vaidya
Pritish Vaidya

Reputation: 22189

Considering the above code I think you should use the redisClient in the following code section if you are creating it as

**redisClient**.on("message", function(channel, message) {
        console.log("New message: " + message + ". In channel: " + channel);
        socket.emit(channel, message);
    });

so that the actionSubscribe() using the redisClient is used to recive the message

Upvotes: 1

Related Questions