使用快速网关创建 API 网关
介绍
本文将指导您如何使用fast-gateway在NodeJS和express 框架下部署一个简单的API 网关。API网关的优势在于它可以作为中间层,隐藏系统中的其他部分,包括服务,这在微服务架构中非常常见。
用法示例
这是部署后的微服务模型:
首先,安装软件包
yarn add fast-gateway
接下来,定义将要使用的端口。
import * as express from 'express'
import * as gateway from 'fast-gateway'
const portGateway = 5000
const portService1 = 5001
const portService2 = 5002
服务 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)
})
}
内容很简单:我只是用 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)
})
}
之后,只需定义网关并启动服务即可。
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()
在实际应用中,每个服务通常都是一个独立的项目存储库。
接下来,当您访问页面http://localhost:5000/service-1/或http://localhost:5000/service-2/时,它们将被转发到相应的服务。
祝您编程愉快!
如果您觉得这篇文章对您有帮助,请访问我博客上的原文,以支持作者并探索更多有趣的内容。
你可能会对以下几部剧集感兴趣:
文章来源:https://dev.to/chauhoangminhnguyen/create-api-gateway-with-fast-gateway-482o




