.Net Core 基础学习笔记 Ocelot网关配置使用
Posted 别跟我嘻嘻哈哈
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.Net Core 基础学习笔记 Ocelot网关配置使用相关的知识,希望对你有一定的参考价值。
1.添加网关服务本身 swagger配置
services.AddSwaggerGen(options => { options.SwaggerDoc("ApiGateway", new OpenApiInfo { Title = "网关服务", Version = "v1" }); });
2.安装ocelot包
3.添加ocelot配置
services.AddOcelot().AddConsul();
4.配置网关集成swagger选项
var apis = new List<string> { "service1", "service2" }; app .UseSwagger() .UseSwaggerUI(options => { apis.ForEach(m => { options.SwaggerEndpoint($"/{m}/swagger.json", m); }); }); //loggerFactory.a(Configuration.GetSection("Logging")); app.UseOcelot().Wait();
5.添加ocelot 网关配置文件
{ "ReRoutes": [ { "DownstreamPathTemplate": "/service1/swagger.json", "DownstreamScheme": "http", "ServiceName": "Service1", "LoadBalancerOptions": { "Type": "RoundRobin" }, "UseServiceDiscovery": true, "UpstreamPathTemplate": "/service1/swagger.json", "UpstreamScheme": "http", "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ] }, { "DownstreamPathTemplate": "/service2/swagger.json", "DownstreamScheme": "http", "LoadBalancer": "RoundRobin", "ServiceName": "Service2", "UseServiceDiscovery": true, "UpstreamPathTemplate": "/service2/swagger.json", "UpstreamScheme": "http", "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ] }, { "DownstreamPathTemplate": "/service1/api/{url}", "DownstreamScheme": "http", "LoadBalancerOptions": { "Type": "RoundRobin" }, "ServiceName": "Service1", "UseServiceDiscovery": true, "UpstreamPathTemplate": "/service1/api/{url}", "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ] }, { "DownstreamPathTemplate": "/service2/api/{url}", "DownstreamScheme": "http", "LoadBalancer": "RoundRobin", "ServiceName": "Service2", "UseServiceDiscovery": true, "UpstreamPathTemplate": "/service2/api/{url}", "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ] } ], "GlobalConfiguration": { "BaseUrl": null, "ServiceDiscoveryProvider": { "Host": "localhost", "Port": 8500, "Type": "Consul" } } }
6.加载网关ocelot配置文件
Program中: public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); webBuilder.UseUrls("http://localhost:9000"); }) .ConfigureAppConfiguration((hostingContext, builder) => { builder .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) .AddJsonFile("ocelot.json"); });
7.配置ocelot配置文件,启用服务发现,以及请求路由匹配规则,详见json文件
8.踩坑点记录
(1)控制台报错:无法匹配上游路径,检查配置文件无问题
解决:Program中手动指定加载ocelot配置配置,见第6步
(2)ocelot 版本为16.0以上时,配置文件标签为Routes, 16.0以下时为ReRoutes,测试使用16.0版本
控制台报错 无法从程序集加载类型XXX,猜测加载的是16.0之前的配置类型,最后降级至15.0 控制台不报此错误
(3)不启用服务发现必须指定下游地址,启用服务发现必须添加服务名 以及服务发现配置。
(4) 服务路由需加服务别名,用于网关匹配 请求哪个服务
(5) 负载均衡配置失效 :"LoadBalancer": "RoundRobin",指定本地下游地址也有同样问题,一样的解决方式
解决:使用另一种配置写法: "LoadBalancerOptions": {
"Type": "RoundRobin"
},
以上是关于.Net Core 基础学习笔记 Ocelot网关配置使用的主要内容,如果未能解决你的问题,请参考以下文章
asp.net core网关Ocelot的简单介绍& Ocelot集成Identity认证