2.3微服务-核心架构 ocelot+consul
微服务核心架构 ocelot+consul
一、在Getaway项目引入Ocelot.Provider.Consul neget包
<PackageReference Include="Ocelot.Provider.Consul" Version="19.0.2" />
二、添加consul服务组件,在configuration.json文件配置consul
Program.cs
builder.Services.AddOcelot() //添加ocelot服务组件 .AddConsul();//添加consul服务组件
configuration.json
{ "Routes": [ { "UpstreamPathTemplate": "/{url}", "UpstreamHttpMethod": [ "Get", "Post" ], "DownstreamPathTemplate": "/{url}", //通配路由 "DownstreamScheme": "http", "UseServiceDiscovery": true, //是否使用服务实列 "ServiceName": "users", //consul 服务名称 "LoadBalancerOptions": { "Type": "CustomPollingLoadBalancer" //RoundRobin 轮询 / LeastConnection 最少连接数 / NoLoadBalance 不负载均衡 / CookieStickySessions 会话粘滞 }, "Priority": 0 // 路由权重,通配默认0,不可修改 } ], "GlobalConfiguration": { "BaseUrl": "http://localhost:6299", //网关对外地址 "ServiceDiscoveryProvider": { "Host": "192.168.1.9", //consul地址 "Port": 8500, //consul端口 "Type": "Consul" //consul提供服务发现,每次请求去consul } } }
三、启动网关服务,测试轮询策略成功
扩展一:ocelot 配置文件支持类型,在consul动态配置 、httpapi修改 、扩展数据库修改
consul动态配置
1、添加 AddConfigStoredInConsul() 服务组件,加入配置文件、并配置celotconsul.json
Program.cs
builder.Services.AddOcelot() //添加ocelot服务组件 .AddConsul()//添加consul服务组件 .AddConfigStoredInConsul()// 支持consul动态配置ocelot
builder.Configuration.AddJsonFile("ocelotconsul.json", optional: false, reloadOnChange: true);
celotconsul.json
{ "GlobalConfiguration": { "ServiceDiscoveryProvider": { "Host": "192.168.1.9", "Port": 8500, "ConfigurationKey": "Ocelot_Consul" } } }
2、重新启动网关,在consul keyvalue显示成功
扩展二:网关缓存
1、项目引用ocelot 缓存nuget包 Ocelot.Cache.CacheManager
<PackageReference Include="Ocelot.Cache.CacheManager" Version="19.0.2" />
2、添加 AddCacheManager() 缓存服务组件
Program.cs
builder.Services.AddOcelot() //添加ocelot服务组件 .AddConsul()//添加consul服务组件 .AddConfigStoredInConsul()// 支持consul动态配置ocelot .AddCacheManager(x => //添加ocelot缓存服务组件 { x.WithDictionaryHandle(); });
3、在路由加上缓存配置 FileCacheOptions
configuration.json
{ "Routes": [ { "UpstreamPathTemplate": "/{url}", "UpstreamHttpMethod": [ "Get", "Post" ], "DownstreamPathTemplate": "/{url}", //通配路由 "DownstreamScheme": "http", "UseServiceDiscovery": true, //是否使用服务实列 "ServiceName": "users", //consul 服务名称 "LoadBalancerOptions": { "Type": "CustomPollingLoadBalancer" //RoundRobin 轮询 / LeastConnection 最少连接数 / NoLoadBalance 不负载均衡 / CookieStickySessions 会话粘滞 }, "FileCacheOptions": { "TtlSeconds": 15, //缓存时间 "Region": "UserCache" //缓存区域,清除key }, "Priority": 0 // 路由权重,通配默认0,不可修改 } ], "GlobalConfiguration": { "BaseUrl": "http://localhost:6299", //网关对外地址 "ServiceDiscoveryProvider": { "Host": "192.168.1.9", //consul地址 "Port": 8500, //consul端口 "Type": "Consul" //consul提供服务发现,每次请求去consul } } }