当前位置: 移动技术网 > IT编程>开发语言>.net > 【.NET Core项目实战-统一认证平台】第四章 网关篇-数据库存储配置(2)

【.NET Core项目实战-统一认证平台】第四章 网关篇-数据库存储配置(2)

2018年11月13日  | 移动技术网IT编程  | 我要评论

建厂网,遵义医学院成绩查询,等你爱我5566

【.net core项目实战-统一认证平台】开篇及目录索引

上篇文章我们介绍了如何扩展ocelot网关,并实现数据库存储,然后测试了网关的路由功能,一切都是那么顺利,但是有一个问题未解决,就是如果网关配置信息发生变更时如何生效?以及我使用其他数据库存储如何快速实现?本篇就这两个问题展开讲解,用到的文档及源码将会在github上开源,每篇的源代码我将用分支的方式管理,本篇使用的分支为course2
附文档及源码下载地址:[https://github.com/jinyancao/ctrauthplatform/tree/course2]

一、实现动态更新路由

上一篇我们实现了网关的配置信息从数据库中提取,项目发布时可以把我们已有的网关配置都设置好并启动,但是正式项目运行时,网关配置信息随时都有可能发生变更,那如何在不影响项目使用的基础上来更新配置信息呢?这篇我将介绍2种方式来实现网关的动态更新,一是后台服务定期提取最新的网关配置信息更新网关配置,二是网关对外提供安全接口,由我们需要更新时,调用此接口进行更新,下面就这两种方式,我们来看下如何实现。

1、定时服务方式

网关的灵活性是设计时必须考虑的,实现定时服务的方式我们需要配置是否开启和更新周期,所以我们需要扩展配置类ahphocelotconfiguration,增加是否启用服务和更新周期2个字段。

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容器注入即可。

新建dbconfigurationpoller类,实现ihostedservice接口,详细代码如下。

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

现在我们启动网关项目和测试服务项目,配置网关启用定时器,代码如下。

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://www.lhsxpumps.com/_localhost:7777/ctr/values,可以得到正确地址。

然后我们在数据库执行网关路由修改命令,等10秒后再刷新页面,发现原来的路由失效,新的路由成功。

update ahphreroute set upstreampathtemplate='/cjy/values' where rerouteid=1


看到这个结果是不是很激动,只要稍微改造下我们的网关项目就实现了网关配置信息的自动更新功能,剩下的就是根据我们项目后台管理界面配置好具体的网关信息即可。

2、接口更新的方式

对于良好的网关设计,我们应该是可以随时控制网关启用哪种配置信息,这时我们就需要把网关的更新以接口的形式对外进行暴露,然后后台管理界面在我们配置好网关相关信息后,主动发起配置更新,并记录操作日志。

我们再回顾下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://www.lhsxpumps.com/_localhost:7777/ctrocelot/configuration可以得到我们数据库配置的结果。

我们再使用post的方式修改配置信息,使用postman测试如下,请求后返回状态200(成功),然后测试修改前和修改后路由地址,发现立即生效,可以分别访问http://localhost:7777/cjy/valueshttp://localhost:7777/cjy/values验证即可。然后使用client1获取access_token,请求配置地址,提示401未授权,为预期结果,达到我们最终目的。

到此,我们网关就实现了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);

如果想扩展其他数据库实现,直接参照此源码即可。

三、回顾与预告

本篇我们介绍了2种动态更新配置文件的方法,实现访问不同,各有利弊,正式使用时可以就实际情况选择即可,都能达到我们的预期目标,也介绍了ocelot扩展组件的使用和identityserver4的基础入门信息。然后又扩展了我们mysql数据库的存储方式,增加到了我们网关的扩展里,随时可以根据项目实际情况进行切换。

网关的存储篇已经全部介绍完毕,有兴趣的同学可以在此基础上继续拓展其他需求,下一篇我们将介绍使用redis来重写ocelot里的所有缓存,为我们后续的网关应用打下基础。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网