在 Node JS 中实现微服务架构
📍 简介
🙂 正如我们在之前的博客“单体架构 vs. 微服务:一种实用方法”中讨论过的。但今天我们将在 NodeJS 中实现微服务架构。
👉 您可以使用任何技术,例如 Spring、Python 等。但我们将使用 NodeJS 进行演示。
📍 目录结构
🙂 您可以在这里找到GitHub Repo(运行前,请在 Order、Payment 和 API-Gateway 目录中运行 npm install)。我们有两个使用 API 网关的服务:Order 和 Payment。
NodeJS_Microservices
|
---> 订单
|
------> server.js (运行于 8081 端口)
|
---> 付款
|
------> server.js (运行于 8082 端口)
|
---> API 网关
|
------> server.js (运行于 9091 端口)
🔥 我们的服务结构如下:-
📍 实现
🙂 每当客户端向 API 网关发出请求时,我们都定义了一些路由(使用前缀),将请求重定向到相应的服务(取决于调用哪个路由)。支付和订单服务是独立的,这意味着如果其中一个服务出现故障,另一个服务不会受到影响。
🔥 我们还可以添加身份验证或中间件,这样任何人都无法直接或未经身份验证地调用服务。我们已经实现了一个非常基本的架构。
- 订单服务器.js
const express = require("express");
const app = express();
const port = 8081;
app.get("/order-list", (req,res)=>{
let response = {
data: {
item: [
{
id: 1,
name: 'order-1'
},
{
id: 2,
name: 'order-2'
}
]
}
};
res.status(200).json(response);
});
app.get("/", (req,res)=>{
res.send("Order called");
});
app.listen(port, ()=>{
console.log("Listening at localhost "+ port);
})
- 支付服务器.js
const express = require("express");
const app = express();
const port = 8082;
app.get("/payment-list", (req,res)=>{
let response = {
data: {
item: [
{
id: 1,
name: 'Payment-1'
},
{
id: 2,
name: 'Payment-2'
}
]
}
};
res.status(200).json(response);
});
app.get("/", (req,res)=>{
res.send("Payment called");
});
app.listen(port, ()=>{
console.log("Listening at localhost "+ port);
})
- API网关
const gateway = require("fast-gateway");
const port = 9001;
const server = gateway({
routes: [
{
prefix: "/order",
target: "http://localhost:8081/",
hooks: {}
},
{
prefix: "/payment",
target: "http://localhost:8082/",
hooks: {}
}
]
});
server.get('/mytesting', (req,res)=> {
res.send("Gateway Called");
})
server.start(port).then(server=>{
console.log("Gateway is running "+port);
})
😌 现在,我们可以启动包括网关在内的服务了
📍 我们可以请求http://localhost:9001/order或者http://localhost:9001/payment
🙋 关注我,了解更多深入教程。目前我主要针对初学者,但很快我们会讨论更高级的内容。
请在评论框中发表你的观点。希望对你有帮助。
文章来源:https://dev.to/ssd/implementing-microservice-architecture-in-node-js-1fg3