.Net Core微服務入門全紀錄(完結)——Ocelot與Swagger

xhznl發表於2020-07-16

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/

相關文章