【问题标题】:Can`t get response from redis subscribe无法从 redis subscribe 获得响应
【发布时间】:2020-06-30 21:18:48
【问题描述】:

我是 redis 的新手,我正在尝试在客户端连接到我的应用程序并稍后在订阅时接收它时创建一个发布,以便将此逻辑应用于更多和更复杂的方法,但它是由于某种我无法发现的原因而无法工作。这是我当前的代码:

const client = redis.createClient({
  port: 6379,
  host: '127.0.0.1'
});

io.on( 'connection', ( socket ) => {

  var sub = redis.createClient();
  sub.subscribe( 'connection' );

  client.publish( 'connection', {message: "user has been connected from port '" + port} , function () { console.log( "client connected" ) } )

  sub.on( "message", ( channel, message ) => {
    console.log( "message received: " + message )
    console.log( channel )
  } )

“sub.on”中的所有内容都没有被执行,所以我做错了什么或错过了一些重要的事情,任何提示都会非常感激。

【问题讨论】:

    标签: node.js redis


    【解决方案1】:

    在我看来,发布是在订阅功能完成之前完成的。

    你可以使用这样的东西

    const client = redis.createClient({
      port: 6379,
      host: '127.0.0.1'
    });
    
    io.on( 'connection', ( socket ) => {
    
      var sub = redis.createClient();
      sub.subscribe( 'connection' );
    
     sub.on('subscribe', function(channel, count) {
        client.publish( 'connection', {message: "user has been connected from port '" + port} , function () { console.log( "client connected" ) } )
     });
    
      sub.on( "message", ( channel, message ) => {
        console.log( "message received: " + message )
        console.log( channel )
      } )
    

    这只会在订阅完成后执行发布。

    【讨论】:

      【解决方案2】:

      问题是我试图将对象作为参数传递。 Redis 只接受 publish 上的字符串,所以这是正确有效的实现方式:

      client.publish( 'connection', "{message: 'user has been connected from port '" + port"}" , function ()...
      

      【讨论】:

        猜你喜欢
        • 2020-08-25
        • 2021-07-18
        • 2018-02-20
        • 2020-12-11
        • 1970-01-01
        • 2016-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多