07_NET中Ocelot結合Consult使用

野码發表於2024-04-16

Consul主機:http://localhost:8500

新建子服務:Consul.ServiceA【http://localhost:5011】,Consul.ServiceB【http://localhost:8012】

配置內容(06_NET中使用Consul(服務發現) - 野碼 - 部落格園 (cnblogs.com))

Consul.ServiceA:

[Route("[controller]/[action]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetProduct()
        {
            List<ProductInfo> list = new()
        {
            new() {Id = 1, Name = "商品1"},
            new() {Id = 2, Name = "商品2"}
        };
            return Ok(list);
        }
    }

Consul.ServiceB:

[Route("[controller]/[action]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetProduct()
        {
            List<ProductInfo> list = new()
        {
            new() {Id = 1, Name = "商品3"},
            new() {Id = 2, Name = "商品4"}
        };
            return Ok(list);
        }
    }

Ocelot配置

新建一個專案OcelotSerivce

安裝包:Consul.AspNetCore;Ocelot.Provider.Consul

appsettings.json配置

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Consul": {
    "HostAddress": "http://localhost:8500",//Consul服務地址
    "ServiceAddress": "localhost",//閘道器地址
    "Port": 7162,//閘道器埠
    "ServerName": "OcelotSerivce"//該閘道器在Consul服務的名稱
  }
}
 public class ConsulOption
    {
        public string HostAddress { get; set; }
        public string ServiceAddress { get; set; }
        public int Port { get; set; }
        public string ServerName { get; set; }
    }

註冊Consul

public static class ConsulServiceExtension
    {
        public static IServiceCollection AddConsulService(this IServiceCollection services, IConfiguration configuration)
        {
            //獲取配置檔案資訊
            var consulSection = configuration.GetSection("Consul");
            services.Configure<ConsulOption>(consulSection);
            var consulOption = consulSection.Get<ConsulOption>();

            //新增consul地址
            services.AddConsul(p =>
            {
                p.Address = new Uri(consulOption.HostAddress);
            });

            //註冊consul
            services.AddConsulServiceRegistration(p =>
            {
                p.ID = Guid.NewGuid().ToString();
                p.Name = consulOption.ServerName;
                p.Address = consulOption.ServiceAddress;
                p.Port = consulOption.Port;

                // 健康檢查這邊沒法做,不需要
            });

            return services;
        }
    }

新增ocelot.json配置檔案

{
  "Routes": [
    {
      "UpstreamPathTemplate": "/s/{url}",
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "DownstreamPathTemplate": "/{url}",
      "DownstreamScheme": "http",
      "ServiceName": "Consul.Service", // 子服務在consul內的名稱
      "LoadBalancerOptions": {
        "Type": "RoundRobin"        //輪訓
      }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "https://localhost:7162",//閘道器地址
    "ServiceDiscoveryProvider": {
      "Scheme": "http",
      "Host": "localhost", // consul 主機
      "Port": 8500, //consul 埠
      "Type": "Consul"
    }
  }
}

Program.cs設定

            var builder = WebApplication.CreateBuilder(args);
            // 新增配置檔案,optional:檔案是否可選,reloadOnChange:如果檔案發生更改,是否應過載配置。
            builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
            // 新增Ocelot 服務
            builder.Services.AddOcelot(builder.Configuration).AddConsul();
            builder.Services.AddConsulService(builder.Configuration);

            var app = builder.Build();

            app.UseOcelot().Wait();

            app.Run();

啟動Consul主機,執行Consul.ServiceA,Consul.ServiceB和OcelotSerivce

http://localhost:7162/s/Product/GetProduct

相關文章