API 网关 Ocelot

3471人阅读 2021/6/7 11:00 总访问:651954 评论:0 收藏:0 手机
分类: API

前言

API网关是系统暴露在外部的一个访问入口。就像一个公司的门卫承担着寻址、限制进入、安全检查、位置引导、等等功能。从面向对象设计的角度看,它与外观模式类似。API网关封装了系统内部架构,为每个客户端提供一个定制的API。它可能还具有其它职责,如身份验证、监控、负载均衡、缓存、请求分片与管理、静态响应处理等等。


API网关方式的核心要点是,所有的客户端和消费端都通过统一的网关接入微服务,在网关层处理所有的非业务功能。通常,网关也是提供REST/HTTP的访问API。服务端通过API-GW注册和管理服务。

Ocelot是一个用.NET Core技术实现并且开源的API网关技术,它的功能包括了:路由、请求聚合、服务发现、认证、鉴权、限流熔断、并内置了负载均衡器、Service Fabric、Skywalking等的集成。而且这些功能都只需要简单的配置即可完成。

下载依赖包(版本16.0.0)

Install-Package Ocelot -version 16.0.0

构建一个Ocelot的配置文件

{
  "Routes": [
    {
        //网关转发到下游格式
      "DownstreamPathTemplate": "/api/customers",
      //下游方案
      "DownstreamScheme": "http",
       //下游服务配置
      "DownstreamHostAndPorts": [
        {
            //下游地址
          "Host": "localhost",
          //下游端口号
          "Port": 9001
        }
      ],
       //上游Api请求格式
      "UpstreamPathTemplate": "/customers",
      //上下游支持请求方法
      "UpstreamHttpMethod": [ "Get" ]
    },
    {
      "DownstreamPathTemplate": "/api/customers/{id}",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 9001
        }
      ],
      "DownstreamPort": 9001,
      "UpstreamPathTemplate": "/customers/{id}",
      "UpstreamHttpMethod": [ "Get" ]
    }
  ],
  //全局
  "GlobalConfiguration": {
    "RequestIdKey": "OcRequestId",
    //管理路径
    "AdministrationPath": "/administration"
  }
}

添加配置文件的使用

在Program文件中的 CreateHostBuilder

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
               .ConfigureAppConfiguration((hostingContext, config) =>
               {
                   //添加配置文件的使用
                   config
                       .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                       .AddJsonFile("configuration.json")
                       .AddEnvironmentVariables();
               })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    //修改启动端口号
                    webBuilder.UseUrls("http://*:9000");
                });
    }

Startup中添加Ocelot相关的引用

添加 ocelot的服务

services.AddOcelot();

添加中间件

app.UseOcelot();


评价
脚踏实地,一步一个脚印
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术