簡介 主要是採用identity Server4 和ocelot 加上consul 實現簡單的客戶端模式 開發準備 環境準備 下載並安裝Consul具體請參考前幾篇的內容 項目介紹 創建ocelotServerTest項目 創建IdentityServer4Test項目 創建consulServer ...
簡介
主要是採用identity Server4 和ocelot 加上consul 實現簡單的客戶端模式
開發準備
環境準備
- 下載並安裝Consul具體請參考前幾篇的內容
項目介紹
- 創建ocelotServerTest項目
- 創建IdentityServer4Test項目
- 創建consulServer項目(API項目)
1.創建Consulserver項目
參考該地址進行創建:微服務(入門二):netcore通過consul註冊服務
2.創建identityServer項目
參考該地址進行創建:微服務(入門四):identityServer的簡單使用(客戶端授權)
3.創建ocelotServerTest項目
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當中的數據,可正常返回數據