事实证明,一位同事已经在我们的电子商务网站上使用了一个解决方案。你只需从你的网络服务继承,用一些不同的设置覆盖 GetWebRequest 函数,你就完成了。
class SafeMyWebService : MyWS.Service
{
private static int _lastBindPortUsed;
protected override WebRequest GetWebRequest(Uri uri)
{
var webreq = base.GetWebRequest(uri) as HttpWebRequest;
webreq.KeepAlive = true;
webreq.ProtocolVersion = HttpVersion.Version10;
webreq.ServicePoint.MaxIdleTime = 10 * 1000; // milliseconds
webreq.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);
webreq.Timeout = 2000;
webreq.ConnectionGroupName = "MyConnectionGroupName";
return webreq;
}
public static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
int port = Interlocked.Increment(ref _lastBindPortUsed);
Interlocked.CompareExchange(ref _lastBindPortUsed, 5001, 65534);
return remoteEndPoint.AddressFamily == AddressFamily.InterNetwork
? new IPEndPoint(IPAddress.Any, port)
: new IPEndPoint(IPAddress.IPv6Any, port);
}
}
我猜它使用更多资源,但它不会失败。