如何在运行时启用或禁用Polly策略?

3
在定义策略时,我希望能够在运行时禁用或启用策略,而不是在调用站点进行操作,因为我可能有多个调用站点。
这是目前我的方法?
private RetryPolicy<IDisposable> GetRetryPolicy()
{
    if (!this.config.DistributedLockEnabled)
    {
        NoOpPolicy<IDisposable> policy = Policy.NoOp<IDisposable>();
        return policy;
    }

    RetryPolicy<IDisposable> lockPolicy = Policy
        .Handle<TimeoutException>()
        .OrResult<IDisposable>(d => d == null)
        .WaitAndRetry(
            this.config.WorkflowLockHandleRequestRetryAttempts,
            attempt => TimeSpan.FromSeconds(this.config.WorkflowLockHandleRequestRetryMultiplier * Math.Pow(this.config.WorkflowLockHandleRequestRetryBase, attempt)),
            (delegateResult, calculatedWaitDuration, attempt, context) =>
                {
                    if (delegateResult.Exception != null)
                    {
                        this.logger.Information(
                            "Exception {0} attempt {1} delaying for {2}ms",
                            delegateResult.Exception.Message,
                            attempt,
                            calculatedWaitDuration.TotalMilliseconds);
                    }
                });
    return lockPolicy;
}

但是,遗憾的是,这段代码无法编译 :)

谢谢, Stephen

1个回答

5
您可以返回这样的策略:
private static Policy GetRetryPolicy(bool useWaitAndRetry)
    {
        if (!useWaitAndRetry)
        {
            return Policy.NoOp();
        }

        return Policy
            .Handle<Exception>()
            .WaitAndRetry(new[]
            {
                TimeSpan.FromSeconds(1),
                TimeSpan.FromSeconds(2),
                TimeSpan.FromSeconds(3)
            });
    }

这是如何使用它的方式:

将其用于以下操作:

GetRetryPolicy(true).Execute(() =>
            {
                // Process the task here
            });

我认为你通过返回抽象策略已经有所发现。请修复代码,我会接受你的答案。 - Stephen Patten
2
交叉参考还在 https://github.com/App-vNext/Polly/issues/634 进行讨论。将策略作为接口返回也是一种选择:private ISyncPolicy<IDisposable> GetRetryPolicy() { ... } - mountain traveller
@StephenPatten 这段代码有什么问题吗?在 Polly V7.2.3 中编译没有问题。 - xcskilab

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接