Azure 应用服务定期失去与 Azure 虚拟网络上的本地 SQL 数据库的连接,直到应用重新启动

问题描述 投票:0回答:1

我们在 Azure 上托管了一个 Web 应用程序,该应用程序服务在网络选项卡中连接了一个虚拟网络,并禁用了路由所有数据。虚拟网络网关通过站点到站点连接连接到本地网络网关,连接工作正常,我们可以通过 Web 应用程序查询本地数据库。

本地数据库的连接字符串:

Data Source=192.168.xxx.xxx\\Name;Initial Catalog=DBName;Persist Security Info=False;User ID=User;Password=Password;Trusted_Connection=False;Connection Timeout=120;

查询示例代码:

using (var dbConnection = new SqlConnection(AppSettings.DBConnection))
{
    try
    {
        if (dbConnection.State != ConnectionState.Open)
            await dbConnection.OpenAsync();

        string query = "SELECT * FROM dbo.table";

        using (var sqlDataAdapter = new SqlDataAdapter(query, dbConnection))
        {
            DataTable dt = new DataTable();
            sqlDataAdapter.Fill(dt);
            // Custom retrieval from dt
            details.itemDetails = DBHelper.GetListOfObjects<ItemDetail>(dt);
            details.otherDetails = DBHelper.GetListOfObjects<OtherDetail>(dt);
        }
    }
    catch (Exception e)
    {
        throw new Exception($"Could not fetch Item Details{Environment.NewLine}{e.Message}");
    }
}

几天后,我们收到本地数据库的连接错误

修复连接的唯一方法是重新启动 Azure 应用服务。我仍然能够从应用程序服务 Kudu 控制台查询数据库,但是应用程序服务在重新启动之前会出现此错误。我认为它暂时失去连接然后无法重新连接。

本地网络网关存在于美国中北部服务器上,而虚拟网络网关存在于美国西部服务器上,这可能是虚拟网络断开连接的问题吗?

database azure azure-web-app-service azure-virtual-network
1个回答
0
投票

云中的网络不可靠。必须为瞬态故障实施重试逻辑的原因。这是一个使用 Polly 的示例:

using Polly;

...

// Define the policy for handling transient faults
var retryPolicy = Policy
    .Handle<SqlException>()
    .Or<TimeoutException>()
    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));

using (var dbConnection = new SqlConnection(AppSettings.DBConnection))
{
    await retryPolicy.ExecuteAsync(async () =>
    {
        try
        {
            if (dbConnection.State != ConnectionState.Open)
                await dbConnection.OpenAsync();

            string query = "SELECT * FROM dbo.table";

            using (var sqlDataAdapter = new SqlDataAdapter(query, dbConnection))
            {
                DataTable dt = new DataTable();
                sqlDataAdapter.Fill(dt);
                // Custom retrieval from dt
                details.itemDetails = DBHelper.GetListOfObjects<ItemDetail>(dt);
                details.otherDetails = DBHelper.GetListOfObjects<OtherDetail>(dt);
            }
        }
        catch (Exception e)
        {
            throw new Exception($"Could not fetch Item Details{Environment.NewLine}{e.Message}");
        }
    });
}

更多信息:

https://github.com/App-vNext/Polly

© www.soinside.com 2019 - 2024. All rights reserved.