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


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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM