c# - C# Azure:本地运行时如何设置 Azure 超时和重试策略?
问题描述
我正在编写针对 Azure 云运行的 C# 代码。我的应用程序是公开方法但没有 UI 的 ASP.NET Core Web 服务。
有时我想使用 Microsoft Azure Storage Emulator 在本地运行我的代码。当我的代码启动时,首先发生的事情之一是:
var container = new BlobContainerClient(_connectionString, s);
bool exists = await container.ExistsAsync(ct);
if (!exists)
await container.CreateAsync(cancellationToken: ct);
在本地运行时,我有时会忘记启动 Azure Storage Emulator。发生这种情况时,我的代码需要一分钟才能超时并告诉我它无法到达“云”。
我想要实现的是:让程序在本地运行时快速给我很好的错误消息,但在云端实际运行时使用更宽松的超时策略。
我可以通过执行以下操作来减少上述超时:
var blobClientOptions = new BlobClientOptions();
blobClientOptions.Retry.MaxRetries = 0;
var container = new BlobContainerClient(_connectionString, s, blobClientOptions);
...但是当我在真正的云上运行时,我不希望这样;我希望它重试。一种选择可能是像上面那样将重试次数设置为零,但仅在本地运行时。
我有一个特定于开发的配置文件 ( appsettings.Development.json
)。是否可以在配置文件中配置此类超时/重试设置?
还是有其他一些最佳实践方法来完成我寻求的“快速开发失败”行为?
提前致谢!
解决方案
- 创建一个包含 blobstorage 配置的类:
public class BlobStorageConfiguration
{
public string ConnectionString {get; set;}
public int MaxRetries {get; set;}
}
- 在你的
appsettings.Development.json
{
...
"BlobStorageConfiguration": {
"ConnectionString " : "<your_connection_string>",
"MaxRetries ":0
}
...
}
- 在你
Startup.cs
的ConfigureServices
方法中
..
var blobConfig = new BlobStorageConfiguration ();
Configuration.Bind(nameof(BlobStorageConfiguration ), blobConfig);
services.AddSingleton(blobConfig );
..
appsettings.Development.json
现在您可以注入您的配置,如果您在本地运行它,它将获取值:
一些控制器:
[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)
}
推荐阅读
- r - 应用 group_by 和 summarise(sum) 但保留大量附加列
- tensorflow - 即使在冻结所有层之后,神经网络也需要时间来训练
- c++ - C++ 使用源代码、静态存档和其他动态库创建动态库
- c# - 在 c# 中列出 SSL 证书(重新创建 IIS 绑定对话框)
- authentication - 使用 Okta 通过 API 访问后端应用程序
- go - 如何在一个会话中发送多个命令但分别保存输出
- ios - iOS Shoutcast 使用 Swift 访问元数据
- scikit-learn - 尽管有足够的内存,但由于内核不断被杀死,无法在 JupyterLab 上运行 auto-sklearn
- javascript - 如何根据我的时区以特定格式获取日期
- c# - 仅使用名称和类型创建 SqlParameter(未分配值)