服务治理

优质
小牛编辑
126浏览
2023-12-01

服务治理配置

黑白名单

"Server": {
 "Name": "sample",
 "Ip": "192.168.3.11",
 "Port": "5003",
 "Security": {
   "Whitelist": "*", //白名单 格式:ip1|ap2|1p3,默认 *
   "BlackList": "" //黑名单 格式:ip1|ap2|1p3,默认 ""
  }
}

负载策略(服务集群之后才会有作用)

"Consul": {
    "ConnectionString": "192.168.180.55:8500",
    "IsHealthCheck": true,
    "Strategy":"Random" //负载策略 Random(随机算法),Polling(轮询算法)
 }

容错、限流、超时、服务降级等配置

Service:声明一个服务方法 Name 定义服务名称,规则为:proto文件package+service名称
HystrixCommand:容错标记
[Service(Name = "grpc.domain.RpcTest")]
public class HelloService : RpcTest.RpcTestBase
{       
    [HystrixCommand(MethodName = nameof(SayHello), ExcuteTimeoutInMilliseconds = 3000)]
    public override async Task<HelloReponse> SayHello(HelloRequest request, ServerCallContext context)
    {           
        var result = await _cache.GetAsync<string>("a");

        return new HelloReponse()
        {
            Code = 1,
            Msg = "hello simple",
            Result = JsonConvert.SerializeObject(result)
        };
    }        
}

HystrixCommand 配置说明

public class HystrixCommandAttribute : Attribute
{
    public string MethodName { get; set; }

    /// <summary>
    /// 执行超时时间
    /// </summary>
    public int ExcuteTimeoutInMilliseconds { get; set; } = 10000;

    /// <summary>
    /// 最大信号量
    /// </summary>
    public int MaxRequests { get; set; } = 0;

    /// <summary>
    /// 最大信号量的限定时间
    /// 默认1s
    /// </summary>
    public int MaxRequestsTime { get; set; } = 1000;

    /// <summary>
    /// 至少多少请求失败,熔断器才发挥起作用
    /// </summary>
    public int BreakerRequestCircuitBreaker { get; set; } = 10;

    /// <summary>
    /// 是否开启服务降级
    /// </summary>
    public bool EnableServiceDegradation { get; set; }

    /// <summary>
    /// 降级缓存类型
    /// </summary>
    public CacheModel Cache { get; set; } = CacheModel.Memory;

    /// <summary>
    /// 降级缓存时间
    /// 单位 秒
    /// </summary>
    public int ServiceDegradationTimeSpan { get; set; } = 10;
}