1 啥,DNS变了?
<connectionStrings>
<add name="conn" connectionString="server=mssql-testdb.ent.cn;database=数据库名;uid=用户名;password=密码" providerName="System.Data.SqlClient" />
</connectionStrings>
近期DB团队对MSSQL集群的某一台服务器进行升级维护打补丁,应用端需要将这台读库的连接指向另一台。由于我们使用的是域名,因此只需运维临时切换一下dns即可。
2 .NET端DNS缓存
其实,.NET端是有DNS缓存的,它的控制在这里:
ServicePointManager.DnsRefreshTimeout
默认情况下,它的默认值是120s,即两分钟。换句话说,如果运维改了DNS,应用端需要两分钟后才能连接到解析后的新IP地址。
如果迫不及待,我们可以修改这个值变小一些,比如:30s 又或者 直接设置为 0。
ServicePointManager.DnsRefreshTimeout = 30000; // 单位:毫秒
ServicePointManager.DnsRefreshTimeout = 0; // 单位:毫秒
Edison也通过一个小demo测试了一下,120s 一秒不多一秒不少。对于可以容忍小规模异常的情景,我们的.NET应用程序基本不需要重启,当然也最好在业务低峰期进行dns切换。
关于ServicePointManager
ServicePointManager 是一个静态类,用来创建、维护和删除 ServicePoint 类的实例。
命名空间:System.Net
程序集:System.dll
当应用程序通过 ServicePointManager 对象请求与 Internet 资源统一资源标识符(URI)的连接时,ServicePointManager 将返回一个 ServicePoint 对象,其中包含由 URI 标识的主机和方案的连接信息。 如果该主机和方案存在现有 ServicePoint 对象,则 ServicePointManager 对象返回现有 ServicePoint 对象;否则,ServicePointManager 对象会创建一个新的 ServicePoint 对象。
# C# Sample
Uri myUri = new Uri("http://www.contoso.com/");
ServicePoint mySP = ServicePointManager.FindServicePoint(myUri);
更多内容参考:
https://docs.microsoft.com/zh-cn/dotnet/api/system.net.servicepointmanager?redirectedfrom=MSDN&view=netframework-4.5