在 Node JS 中实现微服务架构

该文介绍了如何在NodeJS环境中实现微服务架构,通过GitHubRepo展示了Order和Payment两个独立服务以及API-Gateway的目录结构。当客户端通过API网关请求时,请求会被路由到对应的服务。文章提供了一个基础的实现示例,强调了服务间的独立性,并鼓励读者探索更高级的实现。
摘要由CSDN通过智能技术生成

📍简介

🙂 正如我们在之前的博客“单体与微服务:一种实用方法”中讨论的那样。但是今天我们要在 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


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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

产品大道

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值