【发布时间】:2017-07-18 04:20:01
【问题描述】:
我有两个节点应用程序/服务一起运行, 1.主应用 2. 第二个应用
主应用程序负责在最后显示来自不同应用程序的所有数据。现在我将第二个应用程序的一些代码放在主应用程序中,现在它可以工作了,但我希望它能够解耦。我的意思是 secnod 应用程序的代码不会在主应用程序中(通过某种方式在运行时注入它)
就像第二个服务注册到主应用程序注入它的代码一样。 它的代码只有两个模块,是否可以在nodejs中完成?
const Socket = require('socket.io-client');
const client = require("./config.json");
module.exports = (serviceRegistry, wsSocket) =>{
var ws = null;
var consumer = () => {
var registration = serviceRegistry.get("tweets");
console.log("Service: " + registration);
//Check if service is online
if (registration === null) {
if (ws != null) {
ws.close();
ws = null;
console.log("Closed websocket");
}
return
}
var clientName = `ws://localhost:${registration.port}/`
if (client.hosted) {
clientName = `ws://${client.client}/`;
}
//Create a websocket to communicate with the client
if (ws == null) {
console.log("Created");
ws = Socket(clientName, {
reconnect: false
});
ws.on('connect', () => {
console.log("second service is connected");
});
ws.on('tweet', function (data) {
wsSocket.emit('tweet', data);
});
ws.on('disconnect', () => {
console.log("Disconnected from blog-twitter")
});
ws.on('error', (err) => {
console.log("Error connecting socket: " + err);
});
}
}
//Check service availability
setInterval(consumer, 20 * 1000);
}
我在主模块中放置了这段代码,我想通过在运行时以某种方式注入来解耦它?示例将非常有帮助...
【问题讨论】:
-
为什么不将你的第二个应用导出为模块,然后你可以在你的主应用中导入它。
-
“通过某种方式在运行时注入”。这就是
require()。 -
你能澄清你想要这个的原因吗?正如一些答案中提到的,解耦是实现这一目标的方法。除非您有充分的理由想要这样做,否则我会说您最好使用解耦的东西 - 微服务、发布/订阅、作业队列,甚至只是记录数据以供记者使用。
标签: javascript node.js express amd microservices