基于多个 DNS 结果的 Java 传出 TCP 连接故障转移
如果我使用 new Socket("unit.domain.com", 100)
建立连接,并且 unit.domain.com
DNS 记录在 A 记录中有多个 IP 地址.. 如果连接失败,Java 是否会像浏览器一样自动连接到列表中的其他地址之一?还是必须手动实施?
If I make a connection using new Socket("unit.domain.com", 100)
and the unit.domain.com
DNS record has multiple IP addresses in the A record.. In the event of a failed connection, Does Java automatically connect to one of the other addresses in the list like the browser does? or does that have to be implemented manually?
不!
通过 new Socket(String, int) 创建套接字会导致类似的解析,
快捷方式
这是地址解析在 Socket c-tor 中执行的
。如果必须重新连接(故障转移),请使用 InetAddress.getAllByName(host) 返回的结果,随机化(或使用循环)并连接到必要的地址。
编辑:此外,如果您需要连接一些可能的失败,您最好使用 Socket 类的 connect 方法并设置超时。 另外请确保关闭甚至失败的套接字(尤其是通道),因为它们可能会泄漏 *Nix 上的 FD。
No!
Creating a socket via new Socket(String, int) results in a resolving like that
which is a shortcut for
The address resolution is performed in the Socket c-tor.
If you have to reconnect (failover) use the result returned by InetAddress.getAllByName(host), randomize (or use round-robin) and connect to the necessary addresses.
Edit: also if you are going to need to connect with some likely failure, you'd be better off using connect method of the Socket class with a timeout. Also make sure you close even failed sockets (and esp. channels) since they may leak a FD on *Nix.