我正在Hapi框架中开发一个node.js服务器。我采用RabbitMQ(amqp)来排队我的任务。但是,一旦发送请求,而不是立即回复请求,将向Rabbit服务器发送一条消息,其中实际功能将作为消费者。然后,消费者应该将结果返回到(请求,回复)函数并让函数回复它。
现在我的解决方案是在我的工作文件中创建一个变量(amqp使用者所在的位置)并将其导出。然后在索引文件(带有路由处理程序的主脚本)中,导入变量。收到某个请求后,它会向RabbitMQ服务器发送一条消息,服务器将更改该变量。然后,返回索引文件,脚本更新变量的值,然后回复它。显然,由于异步,程序会回复先前请求的结果。
我做了一些研究,发现我们不应该在脚本之间共享一些变量。有没有人有办法解决吗?我的目标是我可以将我的amqp消费者放在一个脚本中。一旦我运行脚本,消费者就可以接收任何相应的消息了。然后在我的索引文件中,一旦收到某个请求,它就会向RabbitMQ服务器发送一条消息。然后它应该抓住消费者的结果并回复它。
以下是我的代码:
index.ts
import * as Joi from "joi";
import * as amqp from "amqplib/callback_api";
import * as waitUntil from "wait-until";
import * as repository from "./repository";
import * as worker from "./worker";
// defien variables from internal modules
let greeter = new repository.Greeter();
// register type
import {Register} from "../../interfaces";
// define amqp related stuff
let greeterReply = worker.greeterReply;
// helloWorld config including handler, validate and auth
export let register: Register = (server, options, next) => {
server.route([
{
method: "GET",
path: "/greeter",
config: {
handler: (request, reply) => {
let q: string = "greeter";
let requestQuery = request.query;
let requestString = JSON.stringify(requestQuery);
amqp.connect("amqp://192.168.0.31", (err, conn) => {
conn.createChannel((err, ch) => {
ch.assertQueue(q, {durable: false});
ch.sendToQueue(q, new Buffer(requestString));
});
});
waitUntil(500, 10, function condition() {
greeterReply = worker.greeterReply;
return (greeterReply !== null);
}, function done(result) {
reply(greeterReply);
greeterReply = null;
});
},
validate: {
query: {
name: Joi.string(),
age: Joi.number()
}
},
}
}
]);
next();
};
register.attributes = {
name: "greeter",
version: "1.0"
};
worker.ts
// import external modules
import * as amqp from "amqplib/callback_api";
// import internal modules
import * as repository from "./repository";
import * as indexModule from "./index";
// defien variables from internal modules
let greeter = new repository.Greeter();
export let greeterReply = null;
amqp.connect("amqp://192.168.0.31", (err, conn) => {
conn.createChannel((err, ch) => {
let q: string = "greeter";
ch.assertQueue(q, {durable: false});
ch.consume(q, function (requestString) {
let newRequest = JSON.parse(requestString.content.toString());
console.log("replied via amqp");
let result: string = "how are you";
result = greeter.helloWorld(newRequest.name, newRequest.age);
console.log("the result is: ", result);
greeterReply = result;
}, {noAck: true});
});
});