技术开发 频道

Programming WCF Services:分步操作、实例停用与限流


限流(Throttling)


   限流“允许开发者限制客户端连接数以及服务的负荷。限流可以避免服务的最大化,以及分配与使用重要资源的最大化。引入限流技术后,一旦超出配置的设置值,WCF就会自动地将等待处理的调用者放入到队列中,然后依次从队列中取出。在队列中等待处理调用时,如果客户端的调用超时,客户端就会获得一个TimeoutException异常。每个服务类型都可以应用限流技术,也就是说,它会影响到服务的所有实例以及服务类型的所有终结点。实现方式是为限流与服务使用的每个通道分发器建立关联。”

   限流由ServiceThrottlingBehavior类定义,包括三个重要的属性:MaxConcurrentCalls、MaxConcurrentSessions、MaxConcurrentInstances,它们分别的默认值为16,10和Int.MaxValue。

   在翻译过程中,我在查阅MSDN时,发现MaxConcurrentSessions的默认值为64,这让我感觉很奇怪,莫非作者在这里出现了错误。然而经过我仔细地查阅相关资料,发现在WCF的早期版本中,MaxConcurrentSessions的默认值确实为64,但在2006年6月的CTP版本中已经被修改为16。

   设置限流值可以通过配置文件,也可以通过编码方式。前者例如:
<system.serviceModel> 
<services>
<service name = "MyService" behaviorConfiguration = "ThrottledBehavior">
...
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name = "ThrottledBehavior">
<serviceThrottling
maxConcurrentCalls = "12"
maxConcurrentSessions = "34"
maxConcurrentInstances = "56"
/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
   WCF并没有提供关于限流的特性。但实现该特性的方法非常简单,如下所示:

public class ServiceThrottlingAttribute : Attribute, IServiceBehavior 
{
private ServiceThrottlingBehavior throttle;

public ServiceThrottlingAttribute(
int maxConcurrentCalls,
int maxConcurrentInstances,
int maxConcurrentSessions)
{
this.throttle = new ServiceThrottlingBehavior();
throttle.MaxConcurrentCalls = maxConcurrentCalls;
throttle.MaxConcurrentInstances = maxConcurrentInstances;
throttle.MaxConcurrentSessions = maxConcurrentSessions;
}

#region IServiceBehavior Members

void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase,
System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints,
System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{ }

void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase)
{
ServiceThrottlingBehavior currentThrottle = serviceDescription.Behaviors.Find<ServiceThrottlingBehavior>();
if (currentThrottle == null)
{
serviceDescription.Behaviors.Add(this.throttle);
}
}

void IServiceBehavior.Validate(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase)
{ }

#endregion
}
0
相关文章