我们正在 .NET Core 中构建面向服务的架构。我们决定使用 Ocelot 作为我们的 API 网关。我已将 Ocelot 与 Consul 集成以进行服务发现。现在我正在尝试为所有下游服务创建一个统一的 Swagger UI。
在服务发现之前,我们有这样的 Swagger 设置:
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger(c => { c.RouteTemplate = "{documentName}/swagger.json"; });
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/docs/customer/swagger.json", "Customers Api Doc");
c.SwaggerEndpoint("/docs/employee/swagger.json", "Employee Api Doc");
c.SwaggerEndpoint("/docs/report/swagger.json", "Reports Api Doc");
});
在 Swagger UI 上,这提供了“选择规范”下拉菜单。开发人员喜欢这个功能,我们希望保留它。但是,既然我们已经删除了有利于服务发现的手动配置,我们还希望动态更新这些端点。
使用当前可用的 Swagger 解决方案,这可能吗?我还没有看到与服务发现或能够动态配置 UI 相关的任何内容。想法和建议?
更新
我想出了一个方法来做到这一点。这有点hack-ish,我希望有一种方法可以做到这一点,而不是那么笨拙。
public class Startup
{
static object LOCK = new object();
SwaggerUIOptions options;
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<SwaggerUIOptions>((provider) =>
{
return this.options;
});
services.AddSingleton<IHostedService, SwaggerUIDocsAggregator>();
services.AddSingleton<IConsulDiscoveryService, MyCounsulDiscoveryServiceImplementation>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger(c => { c.RouteTemplate = "{documentName}/swagger.json"; });
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUI(c =>
{
this.options = c;
});
}
}
public class SwaggerUIDocsAggregator : IHostedService
{
static object LOCK = new object();
IConsulDiscoveryService discoveryService;
SwaggerUIOptions options;
Timer timer;
bool polling = false;
int pollingInterval = 600;
public ConsulHostedService(IConsulDiscoveryService discoveryService, SwaggerUIOptions options)
{
this.discoveryService = discoveryService;
this.options = options;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
this.timer = new Timer(async x =>
{
if (this.polling)
{
return;
}
lock (LOCK)
{
this.polling = true;
}
await this.UpdateDocs();
lock (LOCK)
{
this.polling = false;
}
}, null, 0, pollingInterval);
}
public async Task StopAsync(CancellationToken cancellationToken)
{
this.timer.Dispose();
this.timer = null;
}
private async Task UpdateDocs()
{
var discoveredServices = await this.discoveryService.LookupServices();
var urls = new JArray();
foreach (var kvp in discoveredServices)
{
var serviceName = kvp.Key;
if (!urls.Any(u => (u as JObject).GetValue("url").Value<string>().Equals($"/{serviceName}/docs/swagger.json")))
{
urls.Add(JObject.FromObject(new { url = $"/{serviceName}/docs/swagger.json", name = serviceName }));
}
}
this.options.ConfigObject["urls"] = urls;
}
}