如何设置节点来处理redis pub/sub的sses?

rm5edbpk  于 2021-06-09  发布在  Redis
关注(0)|答案(0)|浏览(221)

编辑:一切都好!这是一个有效的例子。只是需要一个条件,根据下面的评论。我更新了代码片段以反映更改。这么多的功能和这么少的代码!我意识到标签旋转是因为连接仍然打开-因为我告诉它保持打开。在更现实的应用程序中,该连接将在后台通过xhrget调用保持打开状态,并通过xhrpost调用发布消息。
所以,我有点工作,但我错过了一些东西,因为标签图标说,页面是不断加载,我的消息是出血的渠道。以下是我所拥有的:

import express from 'express';
import redis from 'redis';

const app = express();
const port = 1244;

const redisOptions = {
  url: 'redis://redis:6379/1'
}
const subscriber = redis.createClient(redisOptions);
const publisher = redis.createClient(redisOptions);

app.get('/', (_req, res) => res.send('Hello World!'))

app.get('/rooms/:roomId', (req, res) => {
  // setup headers for the response in order to get the persistent HTTP connection
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  });
  subscriber.on("message", function (channel, message) {
    // res.write('id: UniqueID\n');
    // res.write('event: add\n');
    // res.write('retry: 10000\n');
    if (req.params.roomId === channel) {
      let data = "Message: " + message + " on channel: " + channel
      res.write('data: ' + data + '\n\n'); // whenever you send two new line characters the message is sent automatically
    }
  });
  subscriber.subscribe(req.params.roomId);
});

app.get('/rooms/:roomId/messages/:foo', (req, res) => {
  publisher.publish(req.params.roomId, `{\"message\":\"Hello from ${req.params.foo}!\"}`);
  return res.status(200).send('ok');
});

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

下面是它在浏览器中的样子:

正如你所看到的那样,pub/sub端的东西似乎正在工作,而服务器发送的事件似乎正在进入浏览器!但是。。。是否存在某种范围界定问题?我似乎不明白node及其基于事件的io是如何工作的。我对诺德还比较陌生。有没有人想过如何“解决”这个问题?感觉很近,但我撞到墙了。

暂无答案!

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

相关问题