【.NET Core項目實戰-統一認證平臺】第四章 網關篇-數據庫存儲配置(2)

原文: 【.NET Core項目實戰-統一認證平臺】第四章 網關篇-數據庫存儲配置(2)

【.NET Core項目實戰-統一認證平臺】開篇及目錄索引

上篇文章咱們介紹瞭如何擴展Ocelot網關,並實現數據庫存儲,而後測試了網關的路由功能,一切都是那麼順利,可是有一個問題未解決,就是若是網關配置信息發生變動時如何生效?以及我使用其餘數據庫存儲如何快速實現?本篇就這兩個問題展開講解,用到的文檔及源碼將會在GitHub上開源,每篇的源代碼我將用分支的方式管理,本篇使用的分支爲course2
附文檔及源碼下載地址:[https://github.com/jinyancao/CtrAuthPlatform/tree/course2]html

1、實現動態更新路由

上一篇咱們實現了網關的配置信息從數據庫中提取,項目發佈時能夠把咱們已有的網關配置都設置好並啓動,可是正式項目運行時,網關配置信息隨時都有可能發生變動,那如何在不影響項目使用的基礎上來更新配置信息呢?這篇我將介紹2種方式來實現網關的動態更新,一是後臺服務按期提取最新的網關配置信息更新網關配置,二是網關對外提供安全接口,由咱們須要更新時,調用此接口進行更新,下面就這兩種方式,咱們來看下如何實現。mysql

一、定時服務方式git

網關的靈活性是設計時必須考慮的,實現定時服務的方式咱們須要配置是否開啓和更新週期,因此咱們須要擴展配置類AhphOcelotConfiguration,增長是否啓用服務和更新週期2個字段。github

namespace Ctr.AhphOcelot.Configuration
{
    /// <summary>
    /// 金焰的世界
    /// 2018-11-11
    /// 自定義配置信息
    /// </summary>
    public class AhphOcelotConfiguration
    {
        /// <summary>
        /// 數據庫鏈接字符串,使用不一樣數據庫時自行修改,默認實現了SQLSERVER
        /// </summary>
        public string DbConnectionStrings { get; set; }

        /// <summary>
        /// 金焰的世界
        /// 2018-11-12
        /// 是否啓用定時器,默認不啓動
        /// </summary>
        public bool EnableTimer { get; set; } = false;

        /// <summary>
        /// 金焰的世界
        /// 2018-11.12
        /// 定時器週期,單位(毫秒),默認30分鐘自動更新一次
        /// </summary>
        public int TimerDelay { get; set; } = 30*60*1000;
    }
}

配置文件定義完成,那如何完成後臺任務隨着項目啓動而一塊兒啓動呢?IHostedService接口瞭解一下,咱們能夠經過實現這個接口,來完成咱們後臺任務,而後經過Ioc容器注入便可。redis

新建DbConfigurationPoller類,實現IHostedService接口,詳細代碼以下。sql

using Microsoft.Extensions.Hosting;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.Repository;
using Ocelot.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Ctr.AhphOcelot.Configuration
{
    /// <summary>
    /// 金焰的世界
    /// 2018-11-12
    /// 數據庫配置信息更新策略
    /// </summary>
    public class DbConfigurationPoller : IHostedService, IDisposable
    {
        private readonly IOcelotLogger _logger;
        private readonly IFileConfigurationRepository _repo;
        private readonly AhphOcelotConfiguration _option;
        private Timer _timer;
        private bool _polling;
        private readonly IInternalConfigurationRepository _internalConfigRepo;
        private readonly IInternalConfigurationCreator _internalConfigCreator;
        public DbConfigurationPoller(IOcelotLoggerFactory factory,
            IFileConfigurationRepository repo,
            IInternalConfigurationRepository internalConfigRepo,
            IInternalConfigurationCreator internalConfigCreator, 
            AhphOcelotConfiguration option)
        {
            _internalConfigRepo = internalConfigRepo;
            _internalConfigCreator = internalConfigCreator;
            _logger = factory.CreateLogger<DbConfigurationPoller>();
            _repo = repo;
            _option = option;
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            if (_option.EnableTimer)
            {//判斷是否啓用自動更新
                _logger.LogInformation($"{nameof(DbConfigurationPoller)} is starting.");
                _timer = new Timer(async x =>
                {
                    if (_polling)
                    {
                        return;
                    }
                    _polling = true;
                    await Poll();
                    _polling = false;
                }, null, _option.TimerDelay, _option.TimerDelay);
            }
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            if (_option.EnableTimer)
            {//判斷是否啓用自動更新
                _logger.LogInformation($"{nameof(DbConfigurationPoller)} is stopping.");
                _timer?.Change(Timeout.Infinite, 0);
            }
            return Task.CompletedTask;
        }

        private async Task Poll()
       {
            _logger.LogInformation("Started polling");

            var fileConfig = await _repo.Get();

            if (fileConfig.IsError)
            {
                _logger.LogWarning($"error geting file config, errors are {string.Join(",", fileConfig.Errors.Select(x => x.Message))}");
                return;
            }
            else
            {
                var config = await _internalConfigCreator.Create(fileConfig.Data);
                if (!config.IsError)
                {
                    _internalConfigRepo.AddOrReplace(config.Data);
                }
            }
            _logger.LogInformation("Finished polling");
        }
    }
}

項目代碼很清晰,就是項目啓動時,判斷配置文件是否開啓定時任務,若是開啓就根據啓動定時任務去從數據庫中提取最新的配置信息,而後更新到內部配置並生效,中止時關閉並釋放定時器,而後再註冊後臺服務。數據庫

//註冊後端服務
builder.Services.AddHostedService<DbConfigurationPoller>();

如今咱們啓動網關項目和測試服務項目,配置網關啓用定時器,代碼以下。c#

public void ConfigureServices(IServiceCollection services)
{
    services.AddOcelot().AddAhphOcelot(option=>
    {
       option.DbConnectionStrings = "Server=.;Database=Ctr_AuthPlatform;User ID=sa;Password=bl123456;";
       option.EnableTimer = true; //啓用定時任務
       option.TimerDelay = 10*000;//週期10秒
    });
}

啓動後使用網關地址訪問http://localhost:7777/ctr/values,能夠獲得正確地址。
後端

而後咱們在數據庫執行網關路由修改命令,等10秒後再刷新頁面,發現原來的路由失效,新的路由成功。api

UPDATE AhphReRoute SET UpstreamPathTemplate='/cjy/values' where ReRouteId=1


看到這個結果是否是很激動,只要稍微改造下咱們的網關項目就實現了網關配置信息的自動更新功能,剩下的就是根據咱們項目後臺管理界面配置好具體的網關信息便可。

二、接口更新的方式

對於良好的網關設計,咱們應該是能夠隨時控制網關啓用哪一種配置信息,這時咱們就須要把網關的更新以接口的形式對外進行暴露,而後後臺管理界面在咱們配置好網關相關信息後,主動發起配置更新,並記錄操做日誌。

咱們再回顧下Ocelot源碼,看是否幫咱們實現了這個接口,查找法Ctrl+F搜索看有哪些地方注入了IFileConfigurationRepository這個接口,驚喜的發現有個FileConfigurationController控制器已經實現了網關配置信息預覽和更新的相關方法,查看源碼能夠發現代碼很簡單,跟咱們以前寫的更新方式如出一轍,那咱們如何使用這個方法呢?

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Ocelot.Configuration.File;
using Ocelot.Configuration.Setter;

namespace Ocelot.Configuration
{
    using Repository;

    [Authorize]
    [Route("configuration")]
    public class FileConfigurationController : Controller
    {
        private readonly IFileConfigurationRepository _repo;
        private readonly IFileConfigurationSetter _setter;
        private readonly IServiceProvider _provider;

        public FileConfigurationController(IFileConfigurationRepository repo, IFileConfigurationSetter setter, IServiceProvider provider)
        {
            _repo = repo;
            _setter = setter;
            _provider = provider;
        }

        [HttpGet]
        public async Task<IActionResult> Get()
        {
            var response = await _repo.Get();

            if(response.IsError)
            {
                return new BadRequestObjectResult(response.Errors);
            }

            return new OkObjectResult(response.Data);
        }

        [HttpPost]
        public async Task<IActionResult> Post([FromBody]FileConfiguration fileConfiguration)
        {
            try
            {
                var response = await _setter.Set(fileConfiguration);

                if (response.IsError)
                {
                    return new BadRequestObjectResult(response.Errors);
                }

                return new OkObjectResult(fileConfiguration);
            }
            catch(Exception e)
            {
                return new BadRequestObjectResult($"{e.Message}:{e.StackTrace}");
            }
        }
    }
}

從源碼中能夠發現控制器中增長了受權訪問,防止非法請求來修改網關配置,Ocelot源碼通過升級後,把不一樣的功能進行模塊化,進一步加強項目的可配置性,減小冗餘,管理源碼被移到了Ocelot.Administration裏,詳細的源碼也就5個文件組成,代碼比較簡單,就不單獨講解了,就是配置管理接口地址,並使用IdentityServcer4進行認證,正好也符合咱們咱們項目的技術路線,爲了把網關配置接口和網關使用接口區分,咱們須要配置不一樣的Scope進行區分,因爲本篇使用的IdentityServer4會在後續篇幅有完整介紹,本篇就直接列出實現代碼,不作詳細的介紹。如今開始改造咱們的網關代碼,來集成後臺管理接口,而後測試經過受權接口更改配置信息且當即生效。

public void ConfigureServices(IServiceCollection services)
{
    Action<IdentityServerAuthenticationOptions> options = o =>
    {
        o.Authority = "http://localhost:6611"; //IdentityServer地址
        o.RequireHttpsMetadata = false;
        o.ApiName = "gateway_admin"; //網關管理的名稱,對應的爲客戶端受權的scope
    };
    services.AddOcelot().AddAhphOcelot(option =>
    {
        option.DbConnectionStrings = "Server=.;Database=Ctr_AuthPlatform;User ID=sa;Password=bl123456;";
        //option.EnableTimer = true;//啓用定時任務
        //option.TimerDelay = 10 * 000;//週期10秒
    }).AddAdministration("/CtrOcelot", options);
}

注意,因爲Ocelot.Administration擴展使用的是OcelotMiddlewareConfigurationDelegate中間件配置委託,因此咱們擴展中間件AhphOcelotMiddlewareExtensions須要增長擴展代碼來應用此委託。

private static async Task<IInternalConfiguration> CreateConfiguration(IApplicationBuilder builder)
{
    //提取文件配置信息
    var fileConfig = await builder.ApplicationServices.GetService<IFileConfigurationRepository>().Get();
    var internalConfigCreator = builder.ApplicationServices.GetService<IInternalConfigurationCreator>();
    var internalConfig = await internalConfigCreator.Create(fileConfig.Data);
    //若是配置文件錯誤直接拋出異常
    if (internalConfig.IsError)
    {
        ThrowToStopOcelotStarting(internalConfig);
    }
    //配置信息緩存,這塊須要注意實現方式,由於後期咱們須要改造下知足分佈式架構,這篇不作講解
    var internalConfigRepo = builder.ApplicationServices.GetService<IInternalConfigurationRepository>();
    internalConfigRepo.AddOrReplace(internalConfig.Data);
    //獲取中間件配置委託(2018-11-12新增)
    var configurations = builder.ApplicationServices.GetServices<OcelotMiddlewareConfigurationDelegate>();
    foreach (var configuration in configurations)
    {
        await configuration(builder);
    }
    return GetOcelotConfigAndReturn(internalConfigRepo);
}

新建IdeitityServer認證服務,並配置服務端口6666,並添加二個測試客戶端,一個設置訪問scope爲gateway_admin,另一個設置爲其餘,來分別測試認證效果。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Ctr.AuthPlatform.TestIds4
{
    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.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryClients(Config.GetClients());
        }

        // 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();
            }

            app.UseIdentityServer();
        }
    }

    public class Config
    {
        // scopes define the API resources in your system
        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>
            {
                new ApiResource("api1", "My API"),
                new ApiResource("gateway_admin", "My admin API")
            };
        }

        // clients want to access resources (aka scopes)
        public static IEnumerable<Client> GetClients()
        {
            // client credentials client
            return new List<Client>
            {
                new Client
                {
                    ClientId = "client1",
                    AllowedGrantTypes = GrantTypes.ClientCredentials,

                    ClientSecrets =
                    {
                        new Secret("secret1".Sha256())
                    },
                    AllowedScopes = { "api1" }
                },
                new Client
                {
                    ClientId = "client2",
                    AllowedGrantTypes = GrantTypes.ClientCredentials,

                    ClientSecrets =
                    {
                        new Secret("secret2".Sha256())
                    },
                    AllowedScopes = { "gateway_admin" }
                }
            };
        }
    }
}

配置好認證服務器後,咱們使用PostMan來測試接口調用,首先使用有權限的client2客戶端,獲取access_token,而後使用此access_token訪問網關配置接口。

訪問http://localhost:7777/CtrOcelot/configuration能夠獲得咱們數據庫配置的結果。

咱們再使用POST的方式修改配置信息,使用PostMan測試以下,請求後返回狀態200(成功),而後測試修改前和修改後路由地址,發現當即生效,能夠分別訪問http://localhost:7777/cjy/valueshttp://localhost:7777/cjy/values驗證便可。而後使用client1獲取access_token,請求配置地址,提示401未受權,爲預期結果,達到咱們最終目的。

到此,咱們網關就實現了2個方式更新配置信息,你們能夠根據實際項目的狀況從中選擇適合本身的一種方式使用便可。

2、實現其餘數據庫擴展(以MySql爲例)

咱們實際項目應用過程當中,常常會根據不一樣的項目類型選擇不一樣的數據庫,這時網關也要配合項目需求來適應不一樣數據庫的切換,本節就以mysql爲例講解下咱們的擴展網關怎麼實現數據庫的切換及應用,若是有其餘數據庫使用需求能夠根據本節內容進行擴展。

【.NET Core項目實戰-統一認證平臺】第三章 網關篇-數據庫存儲配置信息(1)中介紹了網關的數據庫初步設計,裏面有個人設計的概念模型,如今使用mysql數據庫,直接生成mysql的物理模型,而後生成數據庫腳本,詳細的生成方式請見上一篇,一秒搞定。是否是有點小激動,原來能夠這麼方便。

新建MySqlFileConfigurationRepository實現IFileConfigurationRepository接口,須要NuGet中添加MySql.Data.EntityFrameworkCore

using Ctr.AhphOcelot.Configuration;
using Ctr.AhphOcelot.Model;
using Dapper;
using MySql.Data.MySqlClient;
using Ocelot.Configuration.File;
using Ocelot.Configuration.Repository;
using Ocelot.Responses;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Ctr.AhphOcelot.DataBase.MySql
{
    /// <summary>
    /// 金焰的世界
    /// 2018-11-12
    /// 使用MySql來實現配置文件倉儲接口
    /// </summary>
    public class MySqlFileConfigurationRepository : IFileConfigurationRepository
    {
        private readonly AhphOcelotConfiguration _option;
        public MySqlFileConfigurationRepository(AhphOcelotConfiguration option)
        {
            _option = option;
        }

        /// <summary>
        /// 從數據庫中獲取配置信息
        /// </summary>
        /// <returns></returns>
        public async Task<Response<FileConfiguration>> Get()
        {
            #region 提取配置信息
            var file = new FileConfiguration();
            //提取默認啓用的路由配置信息
            string glbsql = "select * from AhphGlobalConfiguration where IsDefault=1 and InfoStatus=1";
            //提取全局配置信息
            using (var connection = new MySqlConnection(_option.DbConnectionStrings))
            {
                var result = await connection.QueryFirstOrDefaultAsync<AhphGlobalConfiguration>(glbsql);
                if (result != null)
                {
                    var glb = new FileGlobalConfiguration();
                    //賦值全局信息
                    glb.BaseUrl = result.BaseUrl;
                    glb.DownstreamScheme = result.DownstreamScheme;
                    glb.RequestIdKey = result.RequestIdKey;
                    if (!String.IsNullOrEmpty(result.HttpHandlerOptions))
                    {
                        glb.HttpHandlerOptions = result.HttpHandlerOptions.ToObject<FileHttpHandlerOptions>();
                    }
                    if (!String.IsNullOrEmpty(result.LoadBalancerOptions))
                    {
                        glb.LoadBalancerOptions = result.LoadBalancerOptions.ToObject<FileLoadBalancerOptions>();
                    }
                    if (!String.IsNullOrEmpty(result.QoSOptions))
                    {
                        glb.QoSOptions = result.QoSOptions.ToObject<FileQoSOptions>();
                    }
                    if (!String.IsNullOrEmpty(result.ServiceDiscoveryProvider))
                    {
                        glb.ServiceDiscoveryProvider = result.ServiceDiscoveryProvider.ToObject<FileServiceDiscoveryProvider>();
                    }
                    file.GlobalConfiguration = glb;

                    //提取全部路由信息
                    string routesql = "select T2.* from AhphConfigReRoutes T1 inner join AhphReRoute T2 on T1.ReRouteId=T2.ReRouteId where AhphId=@AhphId and InfoStatus=1";
                    var routeresult = (await connection.QueryAsync<AhphReRoute>(routesql, new { result.AhphId }))?.AsList();
                    if (routeresult != null && routeresult.Count > 0)
                    {
                        var reroutelist = new List<FileReRoute>();
                        foreach (var model in routeresult)
                        {
                            var m = new FileReRoute();
                            if (!String.IsNullOrEmpty(model.AuthenticationOptions))
                            {
                                m.AuthenticationOptions = model.AuthenticationOptions.ToObject<FileAuthenticationOptions>();
                            }
                            if (!String.IsNullOrEmpty(model.CacheOptions))
                            {
                                m.FileCacheOptions = model.CacheOptions.ToObject<FileCacheOptions>();
                            }
                            if (!String.IsNullOrEmpty(model.DelegatingHandlers))
                            {
                                m.DelegatingHandlers = model.DelegatingHandlers.ToObject<List<string>>();
                            }
                            if (!String.IsNullOrEmpty(model.LoadBalancerOptions))
                            {
                                m.LoadBalancerOptions = model.LoadBalancerOptions.ToObject<FileLoadBalancerOptions>();
                            }
                            if (!String.IsNullOrEmpty(model.QoSOptions))
                            {
                                m.QoSOptions = model.QoSOptions.ToObject<FileQoSOptions>();
                            }
                            if (!String.IsNullOrEmpty(model.DownstreamHostAndPorts))
                            {
                                m.DownstreamHostAndPorts = model.DownstreamHostAndPorts.ToObject<List<FileHostAndPort>>();
                            }
                            //開始賦值
                            m.DownstreamPathTemplate = model.DownstreamPathTemplate;
                            m.DownstreamScheme = model.DownstreamScheme;
                            m.Key = model.RequestIdKey;
                            m.Priority = model.Priority ?? 0;
                            m.RequestIdKey = model.RequestIdKey;
                            m.ServiceName = model.ServiceName;
                            m.UpstreamHost = model.UpstreamHost;
                            m.UpstreamHttpMethod = model.UpstreamHttpMethod?.ToObject<List<string>>();
                            m.UpstreamPathTemplate = model.UpstreamPathTemplate;
                            reroutelist.Add(m);
                        }
                        file.ReRoutes = reroutelist;
                    }
                }
                else
                {
                    throw new Exception("未監測到任何可用的配置信息");
                }
            }
            #endregion
            if (file.ReRoutes == null || file.ReRoutes.Count == 0)
            {
                return new OkResponse<FileConfiguration>(null);
            }
            return new OkResponse<FileConfiguration>(file);
        }

        //因爲數據庫存儲可不實現Set接口直接返回
        public async Task<Response> Set(FileConfiguration fileConfiguration)
        {
            return new OkResponse();
        }
    }
}

實現代碼後如何擴展到咱們的網關裏呢?只須要在注入時增長一個擴展便可。在ServiceCollectionExtensions類中增長以下代碼。

/// <summary>
/// 擴展使用Mysql存儲。
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IOcelotBuilder UseMySql(this IOcelotBuilder builder)
{
    builder.Services.AddSingleton<IFileConfigurationRepository, MySqlFileConfigurationRepository>();
    return builder;
}

而後修改網關注入代碼。

public void ConfigureServices(IServiceCollection services)
{
    Action<IdentityServerAuthenticationOptions> options = o =>
    {
        o.Authority = "http://localhost:6611"; //IdentityServer地址
        o.RequireHttpsMetadata = false;
        o.ApiName = "gateway_admin"; //網關管理的名稱,對應的爲客戶端受權的scope
    };
    services.AddOcelot().AddAhphOcelot(option =>
                                       {
                                           option.DbConnectionStrings = "Server=localhost;Database=Ctr_AuthPlatform;User ID=root;Password=bl123456;";
                                           //option.EnableTimer = true;//啓用定時任務
                                           //option.TimerDelay = 10 * 000;//週期10秒
                                       })
        .UseMySql()
        .AddAdministration("/CtrOcelot", options);
}

最後把mysql數據庫插入sqlserver同樣的路由測試信息,而後啓動測試,能夠獲得咱們預期的結果。爲了方便你們測試,附mysql插入測試數據腳本以下。

#插入全局測試信息
insert into AhphGlobalConfiguration(GatewayName,RequestIdKey,IsDefault,InfoStatus)
values('測試網關','test_gateway',1,1);

#插入路由分類測試信息
insert into AhphReRoutesItem(ItemName,InfoStatus) values('測試分類',1);

#插入路由測試信息 
insert into AhphReRoute values(1,1,'/ctr/values','[ "GET" ]','','http','/api/Values','[{"Host": "localhost","Port": 9000 }]','','','','','','','',0,1);

#插入網關關聯表
insert into AhphConfigReRoutes values(1,1,1);

若是想擴展其餘數據庫實現,直接參照此源碼便可。

3、回顧與預告

本篇咱們介紹了2種動態更新配置文件的方法,實現訪問不一樣,各有利弊,正式使用時能夠就實際狀況選擇便可,都能達到咱們的預期目標,也介紹了Ocelot擴展組件的使用和IdentityServer4的基礎入門信息。而後又擴展了咱們mysql數據庫的存儲方式,增長到了咱們網關的擴展裏,隨時能夠根據項目實際狀況進行切換。

網關的存儲篇已經所有介紹完畢,有興趣的同窗能夠在此基礎上繼續拓展其餘需求,下一篇咱們將介紹使用redis來重寫Ocelot裏的全部緩存,爲咱們後續的網關應用打下基礎。

相關文章
相關標籤/搜索