发布于 2026-01-06 0 阅读
0

使用快速网关创建 API 网关

使用快速网关创建 API 网关

介绍

本文将指导您如何使用fast-gatewayNodeJSexpress 框架下部署一个简单的API 网关。API网关的优势在于它可以作为中间层,隐藏系统中的其他部分,包括服务,这在微服务架构中非常常见。

NodeJS API 网关

用法示例

这是部署后的微服务模型:

API网关

首先,安装软件包



yarn add fast-gateway


Enter fullscreen mode Exit fullscreen mode

接下来,定义将要使用的端口。



import * as express from 'express'
import * as gateway from 'fast-gateway'

const portGateway = 5000
const portService1 = 5001
const portService2 = 5002


Enter fullscreen mode Exit fullscreen mode

服务 1定义如下:



const startService1 = (): void => {
  const app = express()
  app.get('/list', (req, res) => {
    const items = [
      {
        id: 1,
        name: 'service 1 value 1',
      },
      {
        id: 2,
        name: 'service 1 value 2',
      },
    ]
    res.status(200).json(items)
  })
  app.get('/', (req, res) => {
    res.send('Service 1 index')
  })

  app.listen(portService1, () => {
    console.log('Service 1 running at http://localhost:' + portService1)
  })
}


Enter fullscreen mode Exit fullscreen mode

内容很简单:我只是用 Express 来启动服务。

服务 2与之类似。



const startService2 = (): void => {
  const app = express()
  app.get('/list', (req, res) => {
    const items = [
      {
        id: 1,
        name: 'service 2 value 1',
      },
      {
        id: 2,
        name: 'service 2 value 2',
      },
    ]
    res.status(200).json(items)
  })

  app.get('/', (req, res) => {
    res.send('Service 2 index')
  })

  app.listen(portService2, () => {
    console.log('Service 2 running at http://localhost:' + portService2)
  })
}


Enter fullscreen mode Exit fullscreen mode

之后,只需定义网关并启动服务即可。



const startGateWay = (): void => {
  const server = gateway({
    routes: [
      {
        prefix: '/service-1',
        target: `http://localhost:${portService1}/`,
      },
      {
        prefix: '/service-2',
        target: `http://localhost:${portService2}/`,
      },
    ],
  })

  server
    .get('/', (req, res) => {
      res.send('Gateway index')
    })
    .get('/about', (req, res) => {
      res.send('Gateway about')
    })

  server.start(portGateway).then(server => {
    console.log('Gateway is running at http://localhost:' + portGateway)
  })
}

startService1()
startService2()
startGateWay()


Enter fullscreen mode Exit fullscreen mode

在实际应用中,每个服务通常都是一个独立的项目存储库。

运行中的服务

接下来,当您访问页面http://localhost:5000/service-1/http://localhost:5000/service-2/时,它们将被转发到相应的服务。

服务 1 运行中

服务 2 运行中

祝您编程愉快!


如果您觉得这篇文章对您有帮助,请访问我博客上的原文,以支持作者并探索更多有趣的内容。

博客博客开发FacebookX


你可能会对以下几部剧集感兴趣:

文章来源:https://dev.to/chauhoangminhnguyen/create-api-gateway-with-fast-gateway-482o