dotnet微服务之API网关Ocelot

前言

Ocelot 是一个基于 .NET 平台的 API 网关,专门设计用于微服务架构。它提供了一种简单而灵活的方式来管理微服务架构中的 API 请求路由、负载均衡、认证、授权和监控等功能。

新建webapi项目并引用最新的Ocelot

新建ocelot.json

{
  "Routes": [
    {
      "UpstreamPathTemplate": "/good/{everything}",
      "UpstreamHttpMethod": [ "Get" ],
      "DownstreamPathTemplate": "/{everything}",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 7027
        }
      ]
    },
    {
      "UpstreamPathTemplate": "/order/{everything}",
      "UpstreamHttpMethod": [ "Get" ],
      "DownstreamPathTemplate": "/{everything}",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 7209
        }
      ]
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "https://localhost:7122"
  }
}

修改Program.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);

builder.Services.AddOcelot();

var app = builder.Build();

app.UseOcelot().Wait();

app.Run();

新建webapi项目GoodApi与OrderApi

将HelloController.cs改为:

using Microsoft.AspNetCore.Mvc;

namespace OrderApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class HelloController : ControllerBase
    {
        private readonly ILogger<HelloController> _logger;

        public HelloController(ILogger<HelloController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public string Get()
        {
            return "Hello GoodApi!" + DateTime.Now.ToString();
        }
    }
}

using Microsoft.AspNetCore.Mvc;

namespace OrderApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class HelloController : ControllerBase
    {
        private readonly ILogger<HelloController> _logger;

        public HelloController(ILogger<HelloController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public string Get()
        {
            return "Hello OrderApi!" + DateTime.Now.ToString();
        }
    }
}

修改ocelot.json中的端口与实际项目一致

同时运行3个项目

访问:localhost:7122/good/Hellolocalhost:7122/order/Hello

显示:

附加说明

ocelot.json中UpstreamPathTemplate是我们访问api网关的路径

DownstreamPathTemplate是网关代理的后端的路径

最新版的配置文件中路由关键字是Routes,不是ReRoutes

作者

吴晓阳(手机:13736969112微信同号)

posted @ 2024-11-18 10:55  shiningrise  阅读(11)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css