网关的作用是负责请求的转发,如下图所示:
当上端(PC、移动端)发送请求时,首先到网关,网关再把请求转发到对应的服务。
上端不需要知道调用的是哪个服务,只要知道网关的地址即可。
下面用代码实例来说明网关的作用和具体用法:
1.创建一个.NetCore的webapi项目,NuGet引用ocelot程序集。
2.Program.cs中更改IHostBuilder方法,将项目的配置文件指向到自定义的配置文件中:
代码如下:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureAppConfiguration(cfg=> {
cfg.AddJsonFile("configuration.json", optional: false, reloadOnChange: true);//将配置文件指向新的文件
});
3.添加新的配置文件configuration.json
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5726
},
{
"Host": "localhost",
"Port": 5727
}
],
"LoadBalancerOptions": {
"Type": "RoundRobin" // 负载均衡 RoundRobin(轮询)/LeastConnection(最少连接数)
},
"UpstreamPathTemplate": "/GateWayTest/{url}",
"UpstreamHttpMethod": [ "Get", "Post" ]
}
]
}
5726、5727是已经启动好的两个webapi程序端口。
UpstreamPathTemplate的值“/GateWayTest/{url}”是自定义的访问路径。
4.修改startup.cs配置项,全部换成ocelot。
完整代码:
public void ConfigureServices(IServiceCollection services)
{
//services.AddControllers();
services.AddOcelot(Configuration).AddConsul();
}
//配置程序的处理流程.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseOcelot().Wait();
//app.UseRouting();
//app.UseAuthorization();
//app.UseEndpoints(endpoints =>
//{
// endpoints.MapControllers();
//});
}
代码修改完成,启动项目。
在浏览器输入网关的地址:http://localhost:9527/GateWayTest/values,网关就实现将请求转发到端口为5726或5727两个webapi服务上。
9527是网关所在服务的端口号,可以人为指定。
到此为止,就实现了网关对请求的转发。