在Node.js中实现微服务架构
📍 简介
🙂 正如我们在之前的博客文章“单体架构 vs 微服务:实用方法”中讨论的那样,今天我们将使用 NodeJS 实现微服务架构。
👉 您可以使用任何技术,例如 Spring、Python 等。但我们将以 NodeJS 为例进行演示。
📍目录结构
🙂 您可以在这里找到GitHub 代码库(运行前请在 Order、Payment 和 API-Gateway 目录下运行 `npm install`)。我们提供了 Order 和 Payment 两个服务,并带有 API 网关。
NodeJS 微服务
|
---> 订单
|
------> 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/singhdevhub/implementing-microservice-architecture-in-node-js-1fg3


