Ocelot
Ocelot是一个用.NET Core实现并且开源的API网关,它功能强大,包括了:路由、请求聚合、服务发现、认证、鉴权、限流熔断、并内置了负载均衡器与Service Fabric、Butterfly Tracing集成。
API网关—— 它是系统的暴露在外部的一个访问入口。这个有点像代理访问的家伙,就像一个公司的门卫承担着寻址、限制进入、安全检查、位置引导、等等功能。
依赖包
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
Consul
在Ocelot已经支持简单的负载功能,也就是当下游服务存在多个结点的时候,Ocelot能够承担起负载均衡的作用。但是它不提供健康检查,服务的注册也只能通过手动在配置文件里面添加完成。这不够灵活并且在一定程度下会有风险。这个时候我们就可以用Consul来做服务发现,它能与Ocelot完美结合。
它是一个一个分布式的,高度可用的系统,
而且开发使用都很简便。它提供了一个功能齐全的控制平面,主要特点是:服务发现、健康检查、键值存储、安全服务通信、多数据中心。
安装
1.官网地址https://www.consul.io/
2.添加到环境变量
执行consul
看是否安装成功
执行consul agent
启动可能会遇到的问题
解决方法
- 配置地址
consul agent -dev -bind 192.168.199.112
Polly
Install-Package Polly
using Polly;
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
namespace PollyDemo.Console
{
class Program
{
static void Main(string[] args)
{
//Policy
// // 1. 指定要处理什么异常
// .Handle<HttpRequestException>()
// // 或者指定需要处理什么样的错误返回
// .OrResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.BadGateway)
// // 2. 指定重试次数和重试策略
// .Retry(5, (exception, retryCount, context) =>
// {
// System.Console.WriteLine($"开始第 {retryCount} 次重试:");
// })
// // 3. 执行具体任务
// .Execute(ExecuteMockRequest);
try
{
Policy.Handle<DivideByZeroException>()
.Retry(5, (ex, count) =>
{
System.Console.WriteLine("执行失败! 重试次数 {0}", count);
System.Console.WriteLine("异常来自 {0}", ex.GetType().Name);
}).Execute(() =>
{
Compute();
});
}
catch (Exception ex)
{
System.Console.WriteLine("重试失败:"+ex.InnerException);
}
System.Console.WriteLine("程序结束,按任意键退出。");
System.Console.ReadKey();
}
static HttpResponseMessage ExecuteMockRequest()
{
// 模拟网络请求
System.Console.WriteLine("正在执行网络请求...");
Thread.Sleep(3000);
// 模拟网络错误
return new HttpResponseMessage(HttpStatusCode.BadGateway);
}
static int Compute()
{
System.Console.WriteLine("正在执行Compute()...");
Thread.Sleep(3000);
int a = 0;
return 1 / a;
}
}
}