我的 Azure 函数间歇性读取连接字符串失败
My Azure Function Intermittantly fails to read the connection string
我有一个运行队列触发器的 azure 函数。存储库具有从 ConnectionStrings 集合中获取连接字符串的方法。
return System.Configuration.ConfigurationManager.ConnectionStrings["MyDataBase"].ToString();
这在大多数情况下工作得很好,但我间歇性地看到这个 returns 一个空异常错误。
有什么办法可以让它更健壮吗?
azure functions有时会无法获取设置吗?
我应该将设置存储在不同的部分吗?
我还想说这每天运行数千次,但我看到这个弹出窗口大约 100 次。
运行时版本:1.0.12299.0
您是否正在阅读每个函数调用的配置?您应该考虑阅读一次(例如使用 Lazy<string>
和 static
)并将其重新用于所有函数调用。
可能是多线程访问代码时存在并发问题。在代码周围放置 lock
也有帮助。 ConfigurationManager.ConnectionStrings
应该是安全的,但可能不在 V1 运行时中。
发布了一个类似的问题 here,但这涉及应用程序设置而不是连接字符串。我不认为使用 CloudConfigurationManager 应该是正确的解决方案。
您也可以尝试将连接字符串放入应用程序设置中,除非您使用的是 Entity Framework。
Connection strings should only be used with a function app if you are using entity framework. For other scenarios use App Settings. Click to learn more.
(via Azure Portal)
不确定这是否也适用于 V1 运行时。
解决方案是为连接字符串添加私有静态字符串。然后只有在失败时才从配置中读取。然后我添加了一个暂停半秒的重试。这基本上消除了这种情况的发生。
private static string connectionString = String.Empty;
private string getConnectionString(int retryCount)
{
if (String.IsNullOrEmpty(connectionString))
{
if (System.Configuration.ConfigurationManager.ConnectionStrings["MyEntity"] != null)
{
connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyEntity"].ToString();
}
else
{
if (retryCount > 2)
{
throw new Exception("Failed to Get Connection String From Application Settings");
}
retryCount++;
getConnectionString(retryCount);
}
}
return connectionString;
}
我不知道这是否完美,但它确实有效。我从每天看到此异常 30 次到 none。
我有一个运行队列触发器的 azure 函数。存储库具有从 ConnectionStrings 集合中获取连接字符串的方法。
return System.Configuration.ConfigurationManager.ConnectionStrings["MyDataBase"].ToString();
这在大多数情况下工作得很好,但我间歇性地看到这个 returns 一个空异常错误。
有什么办法可以让它更健壮吗?
azure functions有时会无法获取设置吗?
我应该将设置存储在不同的部分吗?
我还想说这每天运行数千次,但我看到这个弹出窗口大约 100 次。
运行时版本:1.0.12299.0
您是否正在阅读每个函数调用的配置?您应该考虑阅读一次(例如使用 Lazy<string>
和 static
)并将其重新用于所有函数调用。
可能是多线程访问代码时存在并发问题。在代码周围放置 lock
也有帮助。 ConfigurationManager.ConnectionStrings
应该是安全的,但可能不在 V1 运行时中。
发布了一个类似的问题 here,但这涉及应用程序设置而不是连接字符串。我不认为使用 CloudConfigurationManager 应该是正确的解决方案。
您也可以尝试将连接字符串放入应用程序设置中,除非您使用的是 Entity Framework。
Connection strings should only be used with a function app if you are using entity framework. For other scenarios use App Settings. Click to learn more. (via Azure Portal)
不确定这是否也适用于 V1 运行时。
解决方案是为连接字符串添加私有静态字符串。然后只有在失败时才从配置中读取。然后我添加了一个暂停半秒的重试。这基本上消除了这种情况的发生。
private static string connectionString = String.Empty;
private string getConnectionString(int retryCount)
{
if (String.IsNullOrEmpty(connectionString))
{
if (System.Configuration.ConfigurationManager.ConnectionStrings["MyEntity"] != null)
{
connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyEntity"].ToString();
}
else
{
if (retryCount > 2)
{
throw new Exception("Failed to Get Connection String From Application Settings");
}
retryCount++;
getConnectionString(retryCount);
}
}
return connectionString;
}
我不知道这是否完美,但它确实有效。我从每天看到此异常 30 次到 none。