在 Node JS 中实现微服务架构

📍简介

🙂 正如我们在之前的博客“单体与微服务:一种实用方法”中讨论的那样。但是今天我们要在 NodeJS 中实现微服务架构。

👉 您可以使用任何技术,如 Spring、Python 等。但我们将使用 NodeJS 进行演示。

📍目录结构

🙂 您可以在此处找到GitHub Repo(请在运行前在 Order、Payment 和 API-Gateway 目录中运行 npm install)。我们有两个服务 Order 和 Payment with API Gateway。

NodeJS_微服务

|

---> 订购

|

------> server.js(在端口 8081 上运行)

|

---> 付款

|

------> server.js(在端口 8082 上运行)

|

---> API 网关

|

------> server.js(在端口 9091 上运行)

🔥 我们的服务结构如下所示:-

📍实施

🙂 每当客户端向 API 网关发出请求时,我们都定义了一些路由(使用前缀)将请求重定向到适当的服务(取决于调用的路由)。支付和订单服务是独立的,意味着如果一个失败,其他不会受到影响。

🔥 我们还可以添加 Auth 或 Middlewares,这样任何人都可以直接调用服务或不使用 Authentication。我们已经实现了一个非常基本的架构。

  • 订单服务器.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/orderhttp://localhost:9001/payment


🙋 关注更深入的教程。现在,我的目标是初学者,但很快我们将讨论更高级的东西。

将你的观点放在评论中。希望能帮助到你。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>