文章出處

最近在一個ASP.NET Core站點中遇到一個奇怪問題。當用dotnet run命令啟動站點后,開始的一段時間請求執行速度超慢,有時要超過20秒,有時甚至超過1分鐘,日志中會記錄這樣的錯誤:

System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 40 - Could not open a connection to SQL Server)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)

當這些執行超慢的請求執行完成后(只是超慢,但沒有出現500錯誤),一切就恢復正常,上面的錯誤日志也不再出現。

更奇怪的是這個問題只在Linux服務器上出現,在Windows服務器上不會出現。

在園子里看到“.NET Core中ADO.NET SqlClient的使用與常見問題”博文后,我們懷疑可能是SQL Server數據庫服務器沒有安裝SP3(我們用的是阿里云RDS)。

這個問題,表象上體現的是一個連接超時的錯誤:

Unhandled Exception: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 35 - An internal exception was caught) ---> System.AggregateException: One or more errors occurred. (No such device or address) ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: No such device or address

但是這個錯誤卻是因為SQL Server的版本問題造成的,.NET Core中的SqlClient能支持的SQL Server最小版本為 SQL Server 2008 R2 SP3,如果你的數據庫小于這個版本,就會出現這個異常。

官方的Issues在此:https://github.com/dotnet/corefx/issues/9719

今天晚上突然想到,會不會是數據庫連接字符串寫法的問題,換一種寫法試試。于是將connection string由

"Data Source=server-name;initial Catalog=database-name;user=username;password=password"

改為

"Server=server-name;Database=database-name;user=username;password=password"

之后,問題就神奇地解決了!


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()