Asp.Net Core Ocelot

2022/4/8 20:49:16

本文主要是介绍Asp.Net Core Ocelot,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Asp.Net Core Ocelot

1.1 Ocelot简介

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

(1)配置说明

  • Routes - 告诉Ocelot如何处理上游的请求
  • GlobalConfiguration - 全局配置,此节点的配置允许覆盖Routes里面的配置,你可以在这里进行通用的一些配置信息
  • Downstream - 下游服务配置
  • UpStream - 上游服务配置
  • Aggregates - 服务聚合配置
  • ServiceName, LoadBalancer, UseServiceDiscovery - 配置服务发现
  • AuthenticationOptions - 配置服务认证
  • RouteClaimsRequirement - 配置Claims鉴权
  • RateLimitOptions - 限流配置
  • FileCacheOptions - 缓存配置
  • QosOptions - 服务质量与熔断
  • DownstreamHeaderTransform - 头信息转发

1.2 Asp.Net Core使用Ocelot

(1)新建Peng.Core.ApiGateWay,Install-Package Ocelot

这里还是使用Apollo远程配置

  <ItemGroup>
    <PackageReference Include="Ocelot" Version="18.0.0" />
	<PackageReference Include="Com.Ctrip.Framework.Apollo.Configuration" Version="2.6.2" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
  </ItemGroup>

(2)注入Ocelot,这里还需要添加Cors

builder.Services.AddOcelot(_configuration);

app.UseOcelot().Wait();

image-20220402142432000

(3)配置网关,服务A,服务B启动的IP

image-20220402142603679

(4)配置Apollo

新建一个NameSpace

image-20220402142658861

ocelotconfig.json

{
    "GlobalConfiguration": {
      "BaseUrl": "https://localhost:9000/"
    },
    "Routes": [
      {
        "DownstreamScheme": "https",
        "DownstreamHostAndPorts": [
          {
            "Host": "localhost",
            "Port": "9001"
          }
        ],
        "UpstreamPathTemplate": "/api/a/v1/{controller}",
        "DownstreamPathTemplate": "/api/a/v1/{controller}",
        "UpstreamHttpMethod": [
          "GET",
          "POST",
          "DELETE",
          "PUT",
          "OPTIONS"
        ],
       
        "UseServiceDiscovery": false,
        "LoadBalancerOptions": {
          "Type": "RoundRobin"
        }
      },
      {
        "DownstreamScheme": "https",
        "DownstreamHostAndPorts": [
          {
            "Host": "localhost",
            "Port": "9002"
          }
        ],
        "UpstreamPathTemplate": "/api/b/v1/{controller}",
        "DownstreamPathTemplate": "/api/b/v1/{controller}",
        "UpstreamHttpMethod": [
          "GET",
          "POST",
          "DELETE",
          "PUT",
          "OPTIONS"
        ],
        
        "UseServiceDiscovery": false,
        "LoadBalancerOptions": {
          "Type": "RoundRobin"
        }
      }
    ]
  }

appsetting.json配置Apollo,这里三个服务配置都一样

{
  "Apollo": {
    "AppId": "Peng.Core.Service",
    "Env": "DEV",
    "Namespaces": [ "Shared.json", "ocelotconfig.json" ],
    "MetaServer": "http://192.168.188.180:8080",
    "ConfigServer": [ "http://192.168.188.180:8080/" ]
  }
}

image-20220402142841952

(5)通过网关的IP访问接口

image-20220402150413322



这篇关于Asp.Net Core Ocelot的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程