调用API修改Ocelot的配置文件

May 11, 2018 | netcoreocelot | 410 阅读

Ocelot是一个基于.net core的开源webapi服务网关开源项目,功能比较强大,Github项目地址为:https://github.com/ThreeMammals/Ocelot,关于Ocelot的学习资料可以看看张善友的网站:http://www.csharpkit.com/apigateway.html

Ocelot的路由设置是基于配置文件的,同样在Ocelot中使用Consul做服务发现时,也是基于配置文件,当我们修改路由或者需要往Consul中添加ServiceName的时候,需要修改配置文件,网关服务也需要重启,这当然不是我们想要的。

在张善友的帮助下,得知可以通过调用api的方式来修改Ocelot的配置文件,官方文档:https://ocelot.readthedocs.io/en/latest/features/administration.html,本文以示例的方式来介绍怎样通过调用api的方式修改Ocelot的配置文件。

环境

  • .net core:2.1.4
  • Ocelot:6.0
  • IdentityServer4:2.2.0

准备

使用VS2017创建解决方案UpdateOcelotConfig,并添加三个项目:

  • Client

    1. 控制台项目
    2. 添加Ocelot包引用
  • IdentityService

    1. WebAPI项目
    2. 添加IdentityServer4包引用
  • WebAPIGetway

    1. WebAPI项目
    2. 添加IdentityServer4包引用
    3. 添加Ocelot包引用

项目创建完成后如下图:

IdentityService

该项目使用IdentityService4实现一个认证服务,因为在调用Ocelot的api接口时需要用到认证。
1、首先添加对IdentityService4的NuGet包引用;
2、添加Config.cs类,代码如下:

public class Config
{
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("s2api", "My API")
};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "client",
AllowedGrantTypes =GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "s2api" }
}
};
}
}

3、Startup类修改,代码如下:

public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients());
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
}

4、修改项目的启动端口为9500。

WebAPIGetWay

该项目是使用Ocelot的网关服务,具体实现步骤如下:
1、添加Ocelot和IdentityService4的NuGet包引用;
2、添加Ocelot.json配置文件,内容如下:

{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/values",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 10001
}
],
"UpstreamPathTemplate": "/a/api/values",
"UpstreamHttpMethod": [ "Get" ]
}
],
"GlobalConfiguration": {
"BaseUrl": "http://localhost:10000/"
}
}

3、修改Program.cs类,添加对Ocelot.json文件的引用

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
//add ocelot json config file
.ConfigureAppConfiguration((hostingContext, builder) => {
builder
.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("Ocelot.json")
.AddEnvironmentVariables();
})
.UseStartup<Startup>()
.UseUrls("http://*:10000")
.Build();

4、Startup类修改,代码如下:

public void ConfigureServices(IServiceCollection services)
{
Action<IdentityServerAuthenticationOptions> options = o =>
{
//IdentityService认证服务的地址
o.Authority = "http://localhost:9500";
//IdentityService项目中Config类中定义的ApiName
o.ApiName = "s2api";
o.RequireHttpsMetadata = false;
o.SupportedTokens = SupportedTokens.Both;
//IdentityService项目中Config类中定义的Secret
o.ApiSecret = "secret";
};
services.AddOcelot()
.AddAdministration("/admin", options);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseOcelot().Wait();
}

4、修改项目的启动端口为10000.

使用Postman测试下WebAPIGetway和IdentityService

1、设置解决方案的属性,同时启动两个项目

启动后如下图:

2、在Postman中调用 http://localhost:9500/connect/token,获取token,调用方式为Post,form-data传三个参数:

  • client_id:client
  • client_secret:secret
  • grant_type:client_credentials

调用成功后如下图:

3、在Postman中调用接口 http://localhost:10000/admin/configuration 获取Ocelot的配置,接口路径中的admin是在WebAPIGetway项目中的Startup类中定义的

services.AddOcelot()
.AddAdministration("/admin", options);

该接口请求为Get请求,需要在Headers中设置上面获取的token,格式为:

Authorization:Bearer token

请求成功如下图:

4、在Postman中通过接口 http://localhost:10000/admin/configuration 修改配置,修改和获取配置的接口地址一致,修改时请求为Post,同样在Headers中需要添加token,另外还需要设置Content-Type,格式如下:

Authorization:Bearer token
Content-Type:application/json

请求的body就是调整后的json数据,调用成功回返回200,如下图:

5、在WebAPIGetway项目的运行目录中打开Ocelot的配置文件,验证是否修改成功。

使用代码方式来修改配置文件

通过Postman来进行测试如果能够验证通过,说明WebAPIGetway和IdentityService都运行正常,下面在Client项目中用代码的方式来进行配置文件的修改。Client代码如下:

namespace Client
{
class Program
{
static void Main(string[] args) => MainAsync().GetAwaiter().GetResult();
private static async Task MainAsync()
{
//需要修改的配置
var configuration = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamPathTemplate = "/api/values",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host ="localhost",
Port = 10001,
},
new FileHostAndPort
{
Host ="localhost",
Port = 10002,
}
},
DownstreamScheme = "http",
UpstreamPathTemplate = "/c/api/values",
UpstreamHttpMethod = new List<string> { "Get","Post" }
}
},
GlobalConfiguration = new FileGlobalConfiguration
{
BaseUrl = "http://localhost:10000/"
}
};
// 从元数据中发现客户端
var disco = await DiscoveryClient.GetAsync("http://localhost:9500");
// 请求令牌
var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("s2api");
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
}
var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken);
HttpContent content = new StringContent(JsonConvert.SerializeObject(configuration));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync("http://localhost:10000/admin/configuration", content);
Console.ReadLine();
}
}
}

思考

1、Ocelot文档中介绍可以使用外部的IdentityService服务,也可以用内置的,各有什么优缺点?
2、上面例子中是直接将json数据去做更新,有没有什么弊端?是否应该先获取配置,做修改后再更新?

示例代码

本文的示例代码已经放到Github上:https://github.com/oec2003/StudySamples/tree/master/UpdateOcelotConfig

【转载】Ocelot网关的路由热更新的更多相关文章

  1. YARP+AgileConfig 5分钟实现一个支持配置热更新的代理网关

    YARP 是微软开源的一个反向代理项目,英文名叫 Yet Another Reverse Proxy .所谓反向代理最有名的那就是 nginx 了,没错 YARP 也可以用来完成 nginx 的大部分 ...

  2. (转载)李剑英的CSLight入门指南结合NGUI热更新

    原地址:http://www.xuanyusong.com/archives/3075 李剑英的CSLight入门指南文档撰写者:GraphicQQ: 1065147807 一. CSLIGHT 作者 ...

  3. 新版本vue-cli3.x 无法热更新问题【转载】

    版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/weixin_38644883/articl ...

  4. [转载]Ocelot简易教程(五)之集成IdentityServer认证以及授权

    作者:依乐祝 原文地址:https://www.cnblogs.com/yilezhu/p/9807125.html 最近比较懒,所以隔了N天才来继续更新第五篇Ocelot简易教程,本篇教程会先简单介 ...

  5. [转载]Ocelot简易教程(六)之重写配置文件存储方式并优化响应数据

    作者:依乐祝 原文地址:https://www.cnblogs.com/yilezhu/p/9807125.html 很多人都说配置文件的配置很繁琐,如果存储在数据库就方便很多,可以通过自定义UI界面 ...

  6. [转载]Ocelot简易教程(一)Ocelot是什么

    Ocelot简易教程(一)Ocelot是什么 简单的说Ocelot是一个用.NET Core实现并且开源的API网关技术. 可能你又要问了,什么是API网关技术呢?Ocelot又有什么特别呢?我们又该 ...

  7. React Native拆包及热更新方案 · Solartisan

    作者:solart 版权声明:本文图文为博主原创,转载请注明出处. 随着 React Native 的不断发展完善,越来越多的公司选择使用 React Native 替代 iOS/Android 进行 ...

  8. 【原】Android热更新开源项目Tinker源码解析系列之三:so热更新

    本系列将从以下三个方面对Tinker进行源码解析: Android热更新开源项目Tinker源码解析系列之一:Dex热更新 Android热更新开源项目Tinker源码解析系列之二:资源文件热更新 A ...

  9. 【原】Android热更新开源项目Tinker源码解析系列之一:Dex热更新

    [原]Android热更新开源项目Tinker源码解析系列之一:Dex热更新 Tinker是微信的第一个开源项目,主要用于安卓应用bug的热修复和功能的迭代. Tinker github地址:http ...

随机推荐

  1. js 奇偶判断

    function isOdd(num) { == ; } function isEven(num) { == ; } function isSane(num) { return isEven(num) ...

  2. 与vnpy相关的有用博客网址

    https://blog.csdn.net/Trader_Python/article/list/1

  3. springboot启动配置原理之一(创建SpringApplication对象)

    几个重要的事件回调机制 配置在META-INF/spring.factories ApplicationContextInitializer SpringApplicationRunListener ...

  4. MySQL中的decimal

    MySQL DECIMAL数据类型用于在数据库中存储精确的数值.我们经常将DECIMAL数据类型用于保留准确精确度的列,例如会计系统中的货币数据. 要定义数据类型为DECIMAL的列,请使用以下语法: ...

  5. ubuntu18.04.2LTS下安装和配置MySql数据库 --ubuntu

    1.安装MySql ubuntu@thanlon-Ubuntu:~$ sudo apt install mysql-server 2.mysql安装完成后,默认用户名不是root,为了方便,一般我们需 ...

  6. css3-盒模型display:-webkit-box;的使用

    提到移动布局不得不提到盒模型display:-webkit-box;这个属性,在移动布局中浮动已经不在重要,相反自适应成为主要的需求,所以display:-webkit-box;变得尤为重要. box ...

  7. Redis for linux安装配置之—-源码安装

    一‘redis单实例安装配置1.下载redis源码压缩包,并将其上传至服务器/usr/local2.解压redis源码压缩包  # tar -xzvf redis-3.2.12.tar.gz3.进入r ...

  8. python全局变量

    定义函数里面的叫局部变量,出了函数外面就不能用了 局部变量函数被调用时,他的变量才生效 局部变量定义在内存里面,用完就会被释放,全局变量不会释放 当有相同名的局部变量和全局变量,函数会先找自己的变量, ...

  9. 关于SUID SGID

    pattern 模式 permission 权限 The problem 问题 .-exec 找到的所有文件 variable 变量 一.1.grep sed awk 正则表达式 三大平台 #ifco ...

  10. mongodb安装建议

    1)软件包的选择 确保使用最新的稳定版本.目前我们线上使用的版本是2.4.6.MongoDB软件包下载页面http://www.mongodb.org/downloads. 确保线上环境总是使用64位 ...