增加 Windows Communication Foundation (WCF) 应用程序的容量的一种方法是通过将它们部署到负载均衡的服务器场来横向扩展应用程序。 WCF 应用程序可以使用标准负载均衡技术进行负载均衡,包括软件负载均衡器(例如 Windows 网络负载均衡)以及基于硬件的负载均衡设备。
以下部分讨论了使用各种系统提供的绑定生成的负载均衡 WCF 应用程序的注意事项。
使用基本 HTTP 绑定进行负载均衡
从负载均衡的角度来看,使用BasicHttpBinding进行通信的 WCF 应用程序与其他常见类型的 HTTP 网络流量(如静态 HTML 内容、ASP.NET 页面或 ASMX Web Services)没有区别。 使用此绑定的 WCF 通道本质上是无状态的,并在通道关闭时终止其连接。 因此,这 BasicHttpBinding 非常适合现有的 HTTP 负载均衡技术。
默认情况下,消息 BasicHttpBinding 中发送具有 Keep-Alive
值的连接 HTTP 标头,使客户端能够与支持它们的服务建立持久连接。 此配置提供增强的吞吐量,因为可以重复使用以前建立的连接将后续消息发送到同一服务器。 但是,连接重用可能会导致客户端与负载均衡场中的特定服务器紧密关联,从而减少轮循机制负载均衡的有效性。 如果此行为不可取,可以在服务器上使用具有Keep-Alive
或用户定义的KeepAliveEnabled的CustomBinding属性来禁用 HTTPBinding。 以下示例演示如何使用配置执行此作。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service
name="Microsoft.ServiceModel.Samples.CalculatorService"
behaviorConfiguration="CalculatorServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/servicemodelsamples/service"/>
</baseAddresses>
</host>
<!-- configure http endpoint, use base address provided by host
And the customBinding -->
<endpoint address=""
binding="customBinding"
bindingConfiguration="HttpBinding"
contract="Microsoft.ServiceModel.Samples.ICalculator" />
</service>
</services>
<bindings>
<customBinding>
<!-- Configure a CustomBinding that disables keepAliveEnabled-->
<binding name="HttpBinding" keepAliveEnabled="False"/>
</customBinding>
</bindings>
</system.serviceModel>
</configuration>
使用 .NET Framework 4 中引入的简化配置,可以使用以下简化的配置来实现相同的行为。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<protocolMapping>
<add scheme="http" binding="customBinding" />
</protocolMapping>
<bindings>
<customBinding>
<!-- Configure a CustomBinding that disables keepAliveEnabled-->
<binding keepAliveEnabled="False"/>
</customBinding>
</bindings>
</system.serviceModel>
</configuration>
有关默认终结点、绑定和行为的详细信息,请参阅 WCF 服务的 简化配置 和 简化配置。
使用 WSHttp 绑定和 WSDualHttp 绑定进行负载均衡
WSHttpBinding 和 WSDualHttpBinding 都可以通过对默认绑定配置进行多项修改后使用 HTTP 负载均衡技术进行负载均衡。
关闭安全性上下文制定或使用有状态安全会话。 通过将 EstablishSecurityContext 上的 WSHttpBinding 属性设置为
false
,可关闭安全性上下文制定。 如果使用 WSDualHttpBinding 或需要安全会话,则可以使用有状态安全会话,如 安全会话中所述。 有状态的安全会话使得服务可以保持无状态,因为安全会话的所有状态在每次请求中都会作为保护安全令牌的一部分进行传输。 若要启用有状态安全会话,必须使用CustomBinding或用户定义的Binding,因为系统提供的WSHttpBinding和WSDualHttpBinding没有暴露必要的配置设置。如果关闭安全性上下文制定,还需要关闭服务凭据协商。 若要将其关闭,请将 NegotiateServiceCredential 属性 WSHttpBinding 设置为
false
。 若要禁用服务凭据协商,你可能需要在客户端上显式指定终结点标识。不要使用可靠会话。 默认情况下此功能处于关闭状态。
使 Net.TCP 绑定实现负载平衡
NetTcpBinding 可以使用 IP 层负载均衡技术进行负载均衡。 但是,NetTcpBinding 默认情况下会池化 TCP 连接,以减少连接延迟。 这是干扰负载均衡的基本机制的优化。 用于优化 NetTcpBinding 的主配置值是租约超时,它是连接池设置的一部分。 连接池导致客户端连接与场内特定的服务器关联。 随着这些连接的生存期增加(这一因素由租约超时配置来控制),服务器群中各种服务器的负载分布变得不平衡。 因此,平均通话时间增加。 因此,在负载平衡方案中使用 NetTcpBinding 时,应考虑减少由绑定使用的默认租约超时。 30 秒租约超时是负载均衡方案的合理起点,尽管最佳值依赖于应用程序。 有关通道租约超时和其他传输配额的详细信息,请参阅 传输配额。
为了在负载均衡方案中获得最佳性能,请考虑使用 NetTcpSecurity ( Transport 或 TransportWithMessageCredential) 。