1. 程式人生 > 實用技巧 >C#程式錯連SQL Server映象庫問題

C#程式錯連SQL Server映象庫問題

運維中遇到的一個問題,SQL Server配置了映象,C#程式在連線SQL Servr資料庫時出現登入失敗,應用程式日誌如下:

C#程式錯連SQL Server映象庫問題

SQL Server主庫無異常日誌,映象庫日誌記錄如下:

Login failed for user 'XXX'. Reason: Could not find a login matching the name provided.[CLIENT:XXX.XXX.XXX.XXX]
Error:18456, Serverity:14, State:5.

Login failed for user 'XXX'. Reason: Failed to open the explicitly specified database.[CLIENT:XXX.XXX.XXX.XXX]

Error:18456, Serverity:14, State:38.

以下是出現該問題的web程式配置,
配置1:
web伺服器:.net framework4.5
web.config:timeout=300s,Min Pool Size=10,無";Failover Partner=PartnerServerName".
配置2:
web伺服器:.net framework4.7
web.config:timeout=20s,Min Pool Size=10,無";Failover Partner=PartnerServerName".

微軟的解釋如下:

This issue occurs because of an error in the connection-retry algorithm for mirrored databases.

When the retry-algorithm is used, the data provider waits for the first read (SniReadSync) call to finish. The call is sent to the back-end computer that is running SQL Server, and the waiting time is calculated by multiplying the connection time-out value by 0.08. However, the data provider incorrectly sets a connection to a doomed state if a response is slow and if the first SniReadSync call is not completed before the waiting time expires.
Note The slow response in this case may be triggered either by the server or by network latency.
連結:https://support.microsoft.com/en-us/help/2605597/fix-time-out-error-when-a-mirrored-database-connection-is-created-by-t

出現此問題的原因是映象資料庫的連線重試演算法中存在錯誤,程式第一次連線的等待時間為timeout*0.08,如果響應慢並且在等待時間內未完成,則進行重連,如下:
C#程式錯連SQL Server映象庫問題
連結:https://docs.microsoft.com/zh-cn/sql/database-engine/database-mirroring/connect-clients-to-a-database-mirroring-session-sql-server

解決方案:
1) .NET Framework升級到4.5.2及以上
2)Timeout增大(預期值除以0.08),設定Min Pool Size

已確認通過該方法可以解決這個問題(已應用到生產環境)

如果耐心看完所有資料的,可能會發現微軟的資料上說明配置了映象的sqlserver需要在應用程式連線串中顯式指定Failover Partner,即";Failover Partner=PartnerServerName". 為什麼應用程式會在沒有顯式指定映象庫也會出現重連?
請看《Clarification on the Failover Partner in the connectionstring in Database Mirror setup》這篇文章。

轉載於:https://blog.51cto.com/aimax/2092045