gpt4 book ai didi

C# azure : How to set Azure timeout and retry policy when running locally?

转载 作者:行者123 更新时间:2023-12-03 05:30:22 27 4
gpt4 key购买 nike

我正在编写针对 Azure 云运行的 C# 代码。我的应用程序是一个 ASP.NET Core Web 服务,它公开方法但不公开 UI。

有时我想使用 Microsoft Azure 存储模拟器在本地运行我的代码。当我的代码启动时,首先发生的事情之一是:

var container = new BlobContainerClient(_connectionString, s);
bool exists = await container.ExistsAsync(ct);
if (!exists)
await container.CreateAsync(cancellationToken: ct);

在本地运行时,我有时会忘记启动 Azure 存储模拟器。当发生这种情况时,我的代码需要一分钟的时间才会超时并告诉我它无法到达“云”。

我想要实现的是:让程序在本地运行时快速给出良好的错误消息,但在云端实际运行时使用更宽松的超时策略。

我可以通过执行以下操作来减少上述超时:

var blobClientOptions = new BlobClientOptions();
blobClientOptions.Retry.MaxRetries = 0;
var container = new BlobContainerClient(_connectionString, s, blobClientOptions);

...但是当在真正的云上运行时我不希望这样;我想让它重试。一种选择可能是像上面那样将重试次数设置为零,但仅在本地运行时

我有一个特定于开发的配置文件 (appsettings.Development.json)。是否可以在配置文件中配置此类超时/重试设置?

或者是否有其他最佳实践方法来实现我寻求的“开发中快速失败”行为?

提前致谢!

最佳答案

  • 创建一个包含 blob 存储配置的类:
public class BlobStorageConfiguration  
{
public string ConnectionString {get; set;}
public int MaxRetries {get; set;}
}
  • 在您的appsettings.Development.json
{
...
"BlobStorageConfiguration": {
"ConnectionString " : "<your_connection_string>",
"MaxRetries ":0
}
...
}

  • Startup.csConfigureServices 方法中
..
var blobConfig = new BlobStorageConfiguration ();
Configuration.Bind(nameof(BlobStorageConfiguration ), blobConfig);
services.AddSingleton(blobConfig );
..
  • 现在您可以注入(inject)您的配置,如果您在本地运行它,它将从 appsettings.Development.json 获取值:

一些 Controller :

[Route("api/somthing")]
[ApiController]
public class SomethingController : ControllerBase
private readonly ILogger<SomethingController > logger;

public SomethingController (
ILogger<SomethingController > logger,
BlobStorageConfiguration blobConfig)
{
this.logger = logger;
// use your blobConfig (connectionstring and maxRetries)
}

关于C# azure : How to set Azure timeout and retry policy when running locally?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65950493/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com