首先创建 web 项目
dotnet new web -n ApiGateway
然后安装对应的 nuget 包
dotnet add package Ocelot
dotnet add package Ocelot.Provider.Consul
Program 配置
using Ocelot.Middleware;
using Ocelot.DependencyInjection;
using Ocelot.Provider.Consul;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOcelot().AddConsul().AddConfigStoredInConsul();
builder.Configuration.AddJsonFile("ocelot.json");
var app = builder.Build();
app.UseOcelot().Wait();
app.Run();
然后配置 ocelot.json
{
"Routes": [
{
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
"UseServiceDiscovery": true,
"UpstreamPathTemplate": "/media-service/{url}",
"ServiceName": "MediaService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
},
{
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
"UseServiceDiscovery": true,
"UpstreamPathTemplate": "/dictionary-service/{url}",
"ServiceName": "DictionaryService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
},
{
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
"UseServiceDiscovery": true,
"UpstreamPathTemplate": "/search-service/{url}",
"ServiceName": "SearchService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
},
{
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
"UseServiceDiscovery": true,
"UpstreamPathTemplate": "/user-service/{url}",
"ServiceName": "UserService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
},
{
"DownstreamPathTemplate": "/{url}",
"DownstreamScheme": "http",
"UseServiceDiscovery": true,
"UpstreamPathTemplate": "/content-service/{url}",
"ServiceName": "ContentService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
},
"RouteIsCaseSensitive": false
}
],
"GlobalConfiguration": {
"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 8500,
"PollingInterval": 5000,
"Type": "Consul",
"ConfigurationKey": "API_Gateway"
}
}
}
没有找到注册的服务
因为是获取对应的服务实例时,请求的路径不对,例如我在 consul 中注册了 ContentService,在 ocelot.json 中也配置了 ServiceName 为 ContentService,LoadBalancer 会尝试获取所有可用的实例,
通过向 consul 的 /v1/health/service/content-service
路径,然而这个路径时错误的,所以并不能收到相关的信息
解决方法(Ocelot.Provider.Consul 已经是 归档状态了):服务名不要使用 PascalCase,使用中划线分割单词
服务地址无效
consul 注册的使用服务 Address 应该时 Host 名称,不能是 localhost,也不能带有协议名称 https:// 或者 https:// 等
标签:service,url,Consul,结成,ServiceName,Ocelot,Type From: https://www.cnblogs.com/freesfu/p/17301474.html