asp.net core ocelot
网关
水平扩展、垂直拆分
安装ocelot
1 nuget引入ocelot
2 创建一个空项目

3.Startup.cs
导入
using Ocelot.DependencyInjection; using Ocelot.Middleware;
添加中间件
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddOcelot(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseOcelot(); } }
4.Program.cs
public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) //添加一个独立的Ocelot.json配置文件 .ConfigureAppConfiguration((hostingContext, builder) => { builder .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) .AddJsonFile("Ocelot.json"); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>().UseUrls("http://127.0.0.1:5000"); }); }
5.Ocelot.json
"Routes": [ { //服务地址 "DownstreamPathTemplate": "/api/{url}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "127.0.0.1", "Port": 8001 } ], //客户端请求地址 "UpstreamPathTemplate": "/api/{url}", "UpstreamHttpMethod": [ "get", "post" ] } ]
路由功能
xxx
请求聚合
缓存
1.


2.自定义缓存
负载均衡配置
{ "Routes": [ { //服务地址 "DownstreamPathTemplate": "/api/{url}", "DownstreamScheme": "http", //配置多个服务地址 "DownstreamHostAndPorts": [ { "Host": "127.0.0.1", "Port": 8001 }, { "Host": "127.0.0.1", "Port": 8002 } ], //客户端请求地址 "UpstreamPathTemplate": "/api/{url}", "UpstreamHttpMethod": [ "get", "post" ], //均衡策略:1.LeastConnection 最少连接数,2.RoundRobin 轮询,3.NoLoadBalancer 从配置或服务发现中获取第一个可用服务,4.CookieStickySessions 使用 Cookie 将所有请求粘贴到特定服务器?? "LoadBalancerOptions": { "Type": "RoundRobin" } } ] }
这么配置目前存在一个问题,当后端有一个服务端挂掉,客户端访问挂掉的服务器时不会切换到可用的服务器上。
解决方法:配合consul服务发现
学习完consul再补xxxxxxxxxxxxx
注册发现
ocelot做负载均衡时,如果有一个节点挂掉不会被剔除,负载均衡仍然会把请求分配到挂掉的服务上。所以需要用到注册发现功能
引用包

注册

配置

服务治理
授权鉴权
引入

管道还是用这个,不需要加鉴权授权中间件

service里添加

网关json配置


浙公网安备 33010602011771号