使用 Express 和 Redis 进行异步调用

发布于 2024-11-15 00:42:37 字数 490 浏览 1 评论 0原文

我正在使用 Redis Pub/Sub 将消息从 Node.js 传输到后端服务器。

问题是如何从订阅者消息事件中获取消息以便在快速响应中可访问。这是我应该用中间件处理的事情吗?或者有没有更简单的异步回调方法?

下面是我正在讨论的一个基本示例:

subscriber.on("message", function (channel, message) {
    console.log("received: " + channel + ": " + message);
});

server.get('/', function(req, res){
    publisher.publish(server.uuid, server.uuid + ": message here");
    res.send(message);
});

更新:

通过将带有 id 的响应对象传递到异步队列来解决我自己的问题。

I'm working with Redis Pub/Sub to transport messages from Node.js to a backend server.

The issue is how to get the message from the subscriber message event to be accessible in the express response. Is this something I should take care of with middleware? Or is there an easier way with an async callback?

Here's a basic example of what I'm talking about:

subscriber.on("message", function (channel, message) {
    console.log("received: " + channel + ": " + message);
});

server.get('/', function(req, res){
    publisher.publish(server.uuid, server.uuid + ": message here");
    res.send(message);
});

Update:

Solved my own problem by passing the response object with an id to a async queue.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尹雨沫 2024-11-22 00:42:37

我对 Node.js 只有很少的经验,但是类似于以下内容的东西可以工作。我认为您只需要向服务器发出一个请求,其中包含服务器可以识别的模式的消息。在以下示例中,请求为 http://yoursite.com/msg/some_msg_here

var http = require('http');
var site = http.createClient('127.0.0.1', 80);

subscriber.on("message", function(channel, message)) {
    var req = site.request("GET", "/msg/" + message, {'host': '127.0.0.1'});
    req.end();
}

server.get('/msg', function(req, res){
    var msg = req.params.msg;
    publisher.publish(server.uuid, server.uuid + ": " + msg;
    res.send(msg);

希望这可以作为一个起点(如果不是最终解决方案)有所帮助。

I have only a tiny amount of experience with node.js, however something similar to the following will work. I think you simply need to hit the server with a request that contains the message in a pattern that the server recognises. In the following example the request is http://yoursite.com/msg/some_msg_here.

var http = require('http');
var site = http.createClient('127.0.0.1', 80);

subscriber.on("message", function(channel, message)) {
    var req = site.request("GET", "/msg/" + message, {'host': '127.0.0.1'});
    req.end();
}

server.get('/msg', function(req, res){
    var msg = req.params.msg;
    publisher.publish(server.uuid, server.uuid + ": " + msg;
    res.send(msg);

Hope that helps as a starting point if not a final solution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文