Tips:本篇已加入系列文章閱讀目錄,可點擊查看更多相關文章,
前言
上一篇【.Net Core微服務入門全紀錄(八)——Docker Compose與容器網路】完成了docker-compose.yml檔案的撰寫,最后使用docker compose的一個up指令即可在docker中運行整個復雜的環境,本篇簡單介紹一下Ocelot與Swagger的集成,方便在網關專案中統一查看各個服務的api檔案,
開始
首先,網關專案,服務專案 NuGet安裝Swashbuckle.AspNetCore:

服務專案
Order.API專案Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Order API", Version = "v1", Description = "# order service api..." });
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Description = "在下框中輸入請求頭中需要添加Jwt授權Token:Bearer Token",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme{
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"}
},new string[] { }
}
});
});
services.AddControllers();
......
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime, OrderContext orderContext)
{
......
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Order API V1");
});
app.UseRouting();
......
}
打開專案檔案Order.API.csproj,添加生成檔案的配置,swagger要用到:
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>

Product.API專案也是類似的修改,就不貼了,
網關專案
然后是Ocelot網關專案的Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",
new OpenApiInfo {Title = "Gateway API", Version = "v1", Description = "# gateway api..."});
});
services.AddControllers();
......
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/order/swagger/v1/swagger.json", "Order API V1");
c.SwaggerEndpoint("/product/swagger/v1/swagger.json", "Product API V1");
});
//設定Ocelot中間件
app.UseOcelot().Wait();
}
ocelot.json組態檔,Routes節點下增加2個路由配置,不做授權,限流,熔斷等限制:
{
"DownstreamPathTemplate": "/swagger/v1/swagger.json",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/product/swagger/v1/swagger.json",
"UpstreamHttpMethod": [ "Get" ],
"ServiceName": "ProductService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
},
{
"DownstreamPathTemplate": "/swagger/v1/swagger.json",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/order/swagger/v1/swagger.json",
"UpstreamHttpMethod": [ "Get" ],
"ServiceName": "OrderService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
}
運行測驗
使用docker-compose build:

build完成后啟動:

瀏覽器訪問網關專案:http://localhost:9070/swagger

介面測驗:

此時因為沒有授權所以回傳401,為了方便獲取token,我在IDS4.AuthCenter專案增加了一個客戶端配置:
new Client
{
ClientId = "postman client",
ClientName = "Postman Client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets = { new Secret("postman client secret".Sha256()) },
AllowedScopes = new [] {"orderApiScope", "productApiScope"},
}
使用postman獲取token:

拿到token填入文本框,格式是Bearer xxxxxx,注意空格,這里的提示文字亂碼了,應該是在docker中運行的原因,這個不影響先不管他,

填入token后再次請求介面,就可以正常回傳了:

至此,Ocelot與Swagger的集成就完成了,本篇內容比較簡單,swagger應該大部分人都用過,
最后
這個系列博客就到此結束了,本來也就是入門級別的,再往后可能就是更深入的服務治理,比如日志、監控、鏈路追蹤等;服務的持續集成、持續部署;容器編排(k8s);服務網格(Service Mesh)等等,,,這些都不屬于入門的范圍了,
當然,不是每個公司都適合k8s,也不是每個專案都要做微服務,為了盲目推崇某個技術而去使用它時,它便失去了原本的價值,技術本不分高低,適合自己的就是最好的,感謝關注我的小伙伴們,,,
推薦幾個學習入口:
https://space.bilibili.com/361469957/
https://space.bilibili.com/431596483/
https://github.com/dotnet-architecture/eShopOnContainers
https://docs.microsoft.com/
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/1640.html
標籤:.NET Core
上一篇:【翻譯】.NET 5中的性能改進
