阿延德发布 修改 到戴维·布里昂的 断路器, ,其中他将超时分辨率更改为惰性模型。

private readonly DateTime expiry;

public OpenState(CircuitBreaker outer)
    : base(outer)
{
    expiry = DateTime.UtcNow + outer.timeout;
}

public override void ProtectedCodeIsAboutToBeCalled()
{
    if(DateTime.UtcNow < expiry)
        throw new OpenCircuitException();

    outer.MoveToHalfOpenState();
}

然而, 构造函数可能会失败 因为一个 TimeSpan 可以快速溢出a的最大值 DateTime. 。例如,当断路器的超时时间是TimeSpan的最大值时。

System.ArgumentOutOfRangeException 被捕获

Message="添加或减去的值会导致无法表示的日期时间。"

...

在 System.DateTime.op_Addition(DateTime d, TimeSpan t)

我们如何避免这个问题并保持预期的行为?

有帮助吗?

解决方案

做一点数学题

确定是否 超时时间大于剩余时间 a 的最大值 DateTime 和当前的 DateTime. 。最大 TimeSpan 通常表示 功能上的无限超时 (使其成为“一次性”断路器)。

public OpenState(CircuitBreaker outer)
    : base(outer)
{
    DateTime now = DateTime.UtcNow;
    expiry = outer.Timeout > (DateTime.MaxValue - now) 
        ? DateTime.MaxValue
        : now + outer.Timeout;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top