如何 运行 在同一自定义域上本地配置多个微服务?

How to run multiple microservices configured on same custom domain, locally?

我已经按照这篇文章配置了我的后端: How to deploy multiple micro-services under one API domain with Serverless

我知道可以使用无服务器离线插件一项一项地部署服务。但是该插件在不同的端口上创建了多个迷你API网关。

我的前端不知道。它假设一切都已部署并准备好在一个端口上使用。

比方说,如果我想测试需要有效会话的功能,我无法在本地执行此操作,因为我的会话和功能由 2 个不同的服务管理。

只有在我部署了所有更改后,才能在这种情况下进行任何手动测试。这需要很多时间。

有没有办法在同一个端口上部署所有服务,在单个 API 网关后面?

我不能说我完全理解这个问题,但我会试一试。我假设您的意思是单个 'microservice' 是一个单独的 API,它有自己的子域(例如 service1.yourdomain.com、service2.yourdomain.com 等)。然后您尝试使用无服务器离线在您的机器上进行本地测试。

虽然我不知道这在子域级别如何工作,但似乎有一个基于路径的选项。如前所述 , there is also a plugin that internally routes requests based on their path as well. It seems to basically put a proxy in front of the other api's and forwards to the correct port https://github.com/edis/sls-multi-gateways. Full medium article here: https://aws.plainenglish.io/run-multiple-serverless-applications-d8b38ef04f37.

话虽如此,您始终可以使用 docker 自行设置代理,根据主机名或路径将请求转发到不同端口上的服务 运行。

sls-multi-gateways 包 运行 多个 API 网关。如果你有多个服务,想同时在本地比运行,可以加包。但这不是一个完整的解决方案,因为最终您可能希望后端可以在单个主机上访问。

这意味着您正在添加一个依赖项,它会让您完成一半。

当您在没有此包的情况下尝试在本地 运行 多个网关时,您会收到错误消息,指出端口 3002 已被使用。这是因为 serverless offline 插件将 3002 指定为 lambda 函数的默认端口。

由于我们正在尝试 运行 多个服务,第一个服务将占用 3002,其余服务将无法启动。要解决此问题,您必须告诉 serverless offline 它应该使用哪些端口来通过 specifying the lambdaPort in serverless.yml files for your services 为每个服务部署 lambda 函数。这可以像这样完成:

custom: 
  serverless-offline:
    httpPort: 4001 // this is the port on which the service will run
    lambdaPort: 4100 // this is the port which will be assigned to the first lambda function in the service

因此对于每个服务,端口将为 400n,lambda 端口将为 4n00 如果您的服务中的 lambda 函数少于 100 个,则此模式是安全的。看起来你只需要分配一个端口来支持手动 lambda 调用。

现在您可以 运行 使用 concurrently 并行处理所有服务。 我们现在处于 sls-multi-gateways 的状态。

接下来我们需要的是一个代理。 我将 createHttpProxy 中间件与 express 一起使用。但是您可以根据您的项目进行任何设置。

代理服务的代码如下所示:

const express = require("express");
const {
  createProxyMiddleware,
} = require("http-proxy-middleware");

const port = process.env.PORT || 5000; // the port on which you want to access the backend
const app = express();

app.use(
  `/service2`,
  createProxyMiddleware({
    target: `${urlOfService2}`,
  })
);
app.use(
  `/service1`,
  createProxyMiddleware({
    target: `${urlOfService1}`,
  })
);


app.listen(port, () => {
  console.log(`Proxy service up on ${port}.`);
});