如何在收到消息后删除redis listners

l2osamch  于 2021-06-08  发布在  Redis
关注(0)|答案(0)|浏览(193)

我订阅外部socket从socketapi获取数据,然后发布到redis,有点像下面这样。我要走了 maximum event emitter listeners exceeded error 为了 redis.on 。我不能将redis移动到套接字之外,这样我就无法向套接字发送订阅数据所需的数据。如何解决这个问题。我可以删除on事件中的redis listneer吗?

const socketConnect=()=>{

    // Singleton Method To Avoid Multiple Socket Connections
var SingletonSocket = (function () {
    var instance;

    function createInstance() {
        var object = new WebSocket('url');
        return object;
    }

    return {
        getInstance: function () {
            if (! instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

/**
 * Can Subscribe rto multiple channels
 */

// here the redis subscriber givee us message that a new centralid has been added
const ws = SingletonSocket.getInstance();
const key = 'centralidslist';
const unsubscribechannel="matchunsubscribe";
const channel = "eventchannel"
ws.on('open', async function open() {

 log.debug({
        level: 'info',
         message:"Socket Opened Odd",
        timstamp:momenttz().tz("Asia/Kolkata").format("YYYY-MM-DD HH:mm:ss")
      });

redis.subscribe(channel, unsubscribechannel,async (error, count) => {
    if (error) {
        throw new Error(error);
    }
    log.debug(`Subscribed to ${channel} channel. Listening for updates on the ${channel} channel.`);
    await data.publish(channel,"Publishing First Time"); // publishing the event to the channel so that socket subscription can be started
});

    redis.on('message', async (channel, message) => {

     /// How to remove listener once the message is recieved and done processing

        if(channel==unsubscribechannel)

        {
            ws.send();
            redis.removeListners();  // is it a good practice to do it here ?
        }

        else{
           ws.send();

        }

    });

});

ws.on('error', function(error) {
    log.debug({
        level: 'info',
        message:"Socket Error Unable To Connect To URl"+error,
        timstamp:momenttz().tz("Asia/Kolkata").format("YYYY-MM-DD HH:mm:ss")
      });
});

ws.on('close', function close() {
    log.debug({
        level: 'info',
        message:"Socket Closed",
        timstamp:momenttz().tz("Asia/Kolkata").format("YYYY-MM-DD HH:mm:ss")
      });
    setTimeout(()=>{
        console.log("Trying to Reconnect");
        log.debug({
            level: 'info',
            message:"Trying To Reconnect To Socket",
            timstamp:momenttz().tz("Asia/Kolkata").format("YYYY-MM-DD HH:mm:ss")
          });
        socketConnect()}, 5000)
  });

ws.on('message', async function incoming(message) {

});

}

    socketConnect();

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题