07_NET中Ocelot结合Consult使用

Consul主机:http://localhost:8500

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

配置内容(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

 

posted @ 2024-04-16 12:33  野码  阅读(71)  评论(0编辑  收藏  举报