提问者:小点点

无法从redis subscribe获得响应


我对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”里面的所有内容都没有被执行,所以我做了一些错误的事情,或者遗漏了一些重要的东西,任何提示都将被真正地引用。


共1个答案

匿名用户

在我看来,发布是在subscribe函数完成之前完成的。

你可以用这样的东西

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 )
  } )

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