【问题标题】:Microservice : How can you deploy your Microservices project using an API gateway on windows server微服务:如何使用 Windows 服务器上的 API 网关部署微服务项目
【发布时间】:2022-01-26 02:15:16
【问题描述】:

我创建了两个项目,一个是使用此 JSON 文件的 API 网关:

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/post",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 44309
        }
      ],
      "UpstreamPathTemplate": "/gateway/post",
      "UpstreamHttpMethod": [
        "POST",
        "PUT",
        "GET"
      ]
    }
  ]
}

在微服务方面,我创建了一个继承 Controllerbase 的 PostController,基本上是一个 ApiController:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PostService.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

        namespace PostService.Controllers
        {
            [Route("api/[controller]")]
            [ApiController]
            public class PostController : ControllerBase
            {
                private readonly IPostRepository _postRepository;

                public PostController(IPostRepository postRepository)
                {
                    _postRepository = postRepository;
                }

                [HttpGet]
                public IActionResult Get()
                {
                    var posts = _postRepository.GetPosts();
                    return new OkObjectResult(posts);
                }

            }
        }

当我运行项目时,打开了两个浏览器,第一个是 ApiGateway,另一个浏览器是微服务在 localhost 的 44309 端口上运行的地方。我在 api 网关的地址栏中运行它:

https://localhost:44342/gateway/post

很棒的是我的 PostController 中的 Get 方法被调用并正确返回数据。

但是,如果我想在 windows 服务器上运行或部署这些项目,这将如何在 windows 服务器上工作。我需要在我的 ocelot.json 文件中更改什么,或者保持不变还是需要将这些值更改为远程 IP 和端口:

    "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 44309
        }
      ],

那么有人可以为我指出如何在 Windows 服务器上部署它以便 Web 或移动应用程序可以访问 APIGateway 的正确方向吗?

【问题讨论】:

    标签: c# microservices webapi


    【解决方案1】:

    要将其部署在 Windows Server 上,您需要在 IIS 上创建两个网站,一个用于 API 网关,一个用于微服务。 API 网关站点应侦听 https 端口 443 和任何 IP 地址。微服务可以监听你选择的任何端口,但不需要为 https 配置它,因为网关和微服务之间的通信是服务器本地的。微服务应该只监听 127.0.0.1 和 [::1] IP 地址,因为微服务只能通过 API 网关访问。所以你的 ocelot.json 可以是:

    {
      "Routes": [
        {
          "DownstreamPathTemplate": "/api/post",
          "DownstreamScheme": "http",
          "DownstreamHostAndPorts": [
            {
              "Host": "localhost",
              "Port": 44309
            }
          ],
          "UpstreamPathTemplate": "/gateway/post",
          "UpstreamHttpMethod": [
            "POST",
            "PUT",
            "GET"
          ]
        }
      ]
    }
    

    不要忘记在端口 44309 或您选择的端口上为 http 配置微服务站点绑定

    【讨论】: