服务如何集成到以Ocelot为中心的微服体系
[TOC]
Consul简介:
Consul,为你的基础设施提供服务发现和服务配置的工具
- 服务发现 Consul的客户端可用提供一个服务,比如 api 或者mysql ,另外一些客户端可用使用Consul去发现一个指定服务的提供者.通过DNS或者HTTP应用程序可用很容易的找到他所依赖的服务
- 健康检查 Consul客户端可用提供任意数量的健康检查,指定一个服务(比如:webserver是否返回了200 OK 状态码)或者使用本地节点(比如:内存使用是否大于90%)
基本命令(Consul启动命令):
- 生成环境命令
consul agent -server -bootstrap-expect 1 -data-dir ./dataCenter -node=s1 -bind=192.168.1.50 -ui -rejoin -client 0.0.0.0
- 开发时命令
consul agent --dev
服务分布式注册:
-
在Startup类的Configure方法加入以下代码片段
-
服务启动时注册:
string ip = Configuration.GetSection("AppSettings:ip").Value;
string port = Configuration.GetSection("AppSettings:port").Value;
string serviceName = "ProjectService";
string serviceId = serviceName + $":{port}";//端口号为在服务集群中区别服务ID
using (var consulClient = new ConsulClient(ConsulConfig))
{
AgentServiceRegistration asr = new AgentServiceRegistration
{
Address = ip,
Port = Convert.ToInt32(port),
ID = serviceId,
Name = serviceName,
Check = new AgentServiceCheck
{
DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1),
HTTP = $"http://{ip}:{port}/v1/api/Health/Get",
Interval = TimeSpan.FromSeconds(10),
Timeout = TimeSpan.FromSeconds(5),
},
};
consulClient.Agent.ServiceRegister(asr).Wait();
}
细节说明
- DeregisterCriticalServiceAfter
表示Consul做健康服务检查失败xx时间后Consul会撤销该服务
- Interval
表示每xx时间做一次检查
- Timeout
服务健康检查超时时间
- HTTP
健康检查接口
服务停止时撤销:
//注销Consul
appLifeTime.ApplicationStopped.Register(() => {
using (var consulClient = new ConsulClient(ConsulConfig)) {
Console.WriteLine("应用退出,开始从consul注销");
consulClient.Agent.ServiceDeregister(serviceId).Wait();
}
});
Consul注册成功时,管理界面呈现该服务为绿标:
Ocelot如何发现服务:
由于服务注册到consul,Ocelot通过集成Consul的服务发现,获取该服务的所有节点,如以下配置:
// chy.project --> service part
{
"DownstreamPathTemplate": "/{url}",
"DownstreamScheme": "http",
"ServiceName": "ProjectService",
//"DownstreamHostAndPorts": [
// {
// "Host": "localhost",
// "Port": 44338
// }
//],
"UseServiceDiscovery": true,
"UpstreamPathTemplate": "/chy.project/{url}",
"UpstreamHttpMethod": [ "Get", "Post", "Delete", "Put" ],
"ReRouteIsCaseSensitive": false,
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 3,
"DurationOfBreak": 10,
"TimeoutValue": 10000
}
}
细节说明
- UseServiceDiscovery
开启服务发现,前提是GlobalConfiguration设置服务发现,如下:
"GlobalConfiguration": {
"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 8500,
"Type": "Consul"
}
}
- ServiceName
指定注册到Consul的服务名称
Ocelot如何热更新配置:
Ocelot提供以下接口用于更新配置:
- 获取配置: http://localhost:6800/admin/configuration 获取到的配置就是这样滴
- 更新配置: http://localhost:6800/admin/configuration 使用Post提交更新的配置
-- 到这里服务已集成到微服体系当中