微服務(入門學習五):identityServer4+ocelot+consul實現簡單客戶端模式

 

 

 

簡介html

  主要是採用identity Server4 和ocelot 加上consul 實現簡單的客戶端模式web

 

 

開發準備json

 環境準備api

  • 下載並安裝Consul具體請參考前幾篇的內容

項目介紹服務器

  • 建立ocelotServerTest項目
  • 建立IdentityServer4Test項目
  • 建立consulServer項目(API項目)  

 

1.建立Consulserver項目app

   參考該地址進行建立:微服務(入門二):netcore經過consul註冊服務負載均衡

2.建立identityServer項目ide

  參考該地址進行建立:微服務(入門四):identityServer的簡單使用(客戶端受權)微服務

3.建立ocelotServerTest項目post

 3.1建立一個webAPI項目

 

 

3.2 修改startUP配置,添加authentication認證

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using netCore;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Consul;
using Ocelot.Provider.Polly;
namespace IdentityServer4Test
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services
                .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)//添加認證
                .AddIdentityServerAuthentication("TestKey", o =>
                {
                    o.Authority = "http://127.0.0.1:3322";//要認證的服務器地址
                    o.RequireHttpsMetadata = false;//不啓用https
                    o.ApiName = "api1";//要認證的服務名稱
                });
            services.AddOcelot(Configuration).AddConsul().AddPolly();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseMvc();
     
            app.UseOcelot().Wait();
            app.UseAuthentication();
        }
    }
}

 

3.3建立ocelot.json文件而且添加AuthenticationOptions

 "AuthenticationOptions": {
        "AuthenticationProviderKey": "TestKey",
        "AllowedScopes": []
      }

 

{
  "ReRoutes": [

    {
      //下游路由模板,真實請求的路徑
      "DownstreamPathTemplate": "/api/{everything}",
      //請求的方式,例如:http,https
      "DownstreamScheme": "http",
      //服務器名稱
      "ServiceName": "zyz1",
      //啓用consul服務
      "UseServiceDiscovery": true,
      //服務熔斷
      "QoSOptions": {
        "ExceptionsAllowedBeforeBreaking": 3, //容許多少次異常請求
        "DurationOfBreak": 5, //熔斷時間,單位爲秒
        "TimeoutValue": 5000 //若是下游請求的處理時間超過多少則自動設置超時
      },
      //"RateLimitOptions": {
      //  "ClientWhitelist": [ "admin" ], // 白名單
      //  "EnableRateLimiting": true, // 是否啓用限流
      //  "Period": "1m", // 統計時間段:1s, 5m, 1h, 1d
      //  "PeriodTimespan": 15, // 多少秒以後客戶端能夠重試
      //  "Limit": 5 // 在統計時間段內容許的最大請求數量
      //},//負載均衡:
      //RoundRobin輪流發送;
      //LeastConnection – 將請求發往最空閒的那個服務器
      //NoLoadBalance – 老是發往第一個請求或者是服務發現
      "LoadBalancerOptions": {
        "Type": "RoundRobin"
      },

      //上游地址配置
      "UpstreamPathTemplate": "/test/{everything}",
      //上游支持的請求類型
      "UpstreamHttpMethod": [ "GET", "POST" ],
      "AuthenticationOptions": {
        "AuthenticationProviderKey": "TestKey",
        "AllowedScopes": []
      }
    },
    {
      "DownstreamPathTemplate": "/api/Token",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "127.0.0.1",
          "Port": 3322
        }
      ],
      "UpstreamPathTemplate": "/GetToken",
      "UpstreamHttpMethod": [ "Get" ]
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "https://localhost:8596",
    //consul服務器地址和ip
    "ServiceDiscoveryProvider": {
      "Host": "localhost",
      "Port": 8500
    }

  }
}

3.4 修改program文件,添加訪問地址,以及ocelot的配置文件

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace IdentityServer4Test
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .UseUrls("http://localhost:8596")
            .ConfigureAppConfiguration(conf =>
            {
                conf.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
            })
           .UseStartup<Startup>();
    }
}

 

 

測試

1.首先開啓consul服務

 

 

 2.接下來把服務註冊到consul當中,啓動ConsulServer

 

 

 

3.啓動IdentityServer4Test和ocelotServerTest服務

 

 

 

4.經過postMan獲取token(正式開發中不會如此使用)

 

 

 5.根據獲取的token去請求Consulserver當中的數據,可正常返回數據

 

 

相關文章
相關標籤/搜索