使用Ocelot做网关
1首先创建一个json的配置文件,文件名随便取,我取Ocelot.json
这个配置文件有两种配置方式,第一种,手动填写 服务所在的ip和端口;第二种,用Consul进行服务发现
第一种如下:
{
"ReRoutes": [
{
//转发处理格式
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
//手动指明ip和端口号
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 6001
}
],
//请求格式
"UpstreamPathTemplate": "/Ocelot_Consul_Service/{url}",
"UpstreamHttpMethod": [ "Get", "Post" ]
}
]
//例如,我的Ocelot ip是127.0.0.1 端口是8888的情况下,
//我请求的是localhost:8888/Ocelot_Consul_Service/values
//会被转到localhost 的6001端口 6001端口对应的是 Ocelot_Consul_Service 对应的webapi
//请求转后的路径是:localhost:6001/api/Ocelot_Consul_Service/values
}
第二种如下:
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/Ocelot_Consul_Service/{url}",
"UpstreamHttpMethod": [ "Get", "Post" ],
//指明服务名
"ServiceName": "Ocelot_Consul_Service",
//指明负载平衡方式
"LoadBalancerOptions": {
"Type": "RoundRobin" //轮询
},
//使用服务发现
"UseServiceDiscovery": true
}
],
//全局配置
"GlobalConfiguration": {
//服务发现的提供者
"ServiceDiscoveryProvider": {
//ip
"Host": "localhost",
//端口
"Port": 8500,
//由Consul提供服务发现
"Type": "Consul"
}
}
}
2.接下来我们要安装Ocelot
install-package Ocelot
3.安装完毕 要在Program.cs文件中使用第一步中创建的json文件,把它读到配置里面去。
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
//解析出从控制台传入的ip和端口号
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.Build();
string ip = config["ip"];
string port = config["port"];
return WebHost.CreateDefaultBuilder(args)
.UseUrls($"http://{ip}:{port}")
//注册应用配置
.ConfigureAppConfiguration((hostingContext,builder)=> {
//false 此文件是否是可选的,不是!true 如果此文件被修改了是否重新加载 是!
builder.AddJsonFile("Ocelot.json", false, true);
})
.UseStartup<Startup>();
}
4.在启动类(startup.cs)文件中添加Ocelot服务
public void ConfigureServices(IServiceCollection services)
{
//这个AddOcelot方法是Ocelot包给IServiceCollection扩展的方法
//如果不使用Consul进行服务发现,只需要services.AddOcelot(configuration)即可
//但是如果使用Consul进行服务发现 后面还要AddConsul()
//要使用AddConsul()必须安装包 Ocelot.Provider.Consul
services.AddOcelot(configuration).AddConsul();
}
一定要注意第4步,使用Consul做服务发现要安装 Ocelot.Provider.Consul 包 并AddConsul()。在实际中 我们要尽量要用Consul进行服务发现。
附上Ocelot文档截图一张如下:

============ 欢迎各位老板打赏~ ===========
与本文相关的文章
- · [转].NET Core开源API网关 – Ocelot中文文档
- · 微服务实战(二):使用API Gateway
- · API网关ocelot特性之聚合
- · Ocelot+Consul+.netcore高可用&动态伸缩
- · .NET Core微服务之基于Ocelot实现API网关服务
- · windows下利用wsl+sshpass 自动发布脚本
- · 单台服务器应用不中断服务热部署滚动更新方案
- · The instance of entity type ‘Customer’ cannot be tracked because another instance with the same key value for {‘Id’} is already being tracked.
- · .NET8实时更新nginx ip地址归属地
- · 解决.NET Blazor子组件不刷新问题
- · .NET8如何在普通类库中引用 Microsoft.AspNetCore
- · 阿里云三种负载均衡的区别

