http://hi.baidu.com/aptsnail/blog/item/7e4c6f3404733e3e5ab5f530.html
限流(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 } 定义的ServiceThrottlingAttribute特性继承了Attribute,并实现了IServiceBehavior接口。在特性内,则使用了ServiceThrottlingBehavior类,以设置限流的相关值。如果要配置服务的限流值,就可以应用该特性,例如: [ServiceThrottling(12, 34, 56)] class MyService : IMyContract,IDisposable { public void MyMethod( ) { ChannelDispatcher dispatcher = OperationContext.Current.Host.ChannelDispatchers[0] as ChannelDispatcher; ServiceThrottle serviceThrottle = dispatcher.ServiceThrottle; Trace.WriteLine("MaxConcurrentCalls = " + serviceThrottle.MaxConcurrentCalls); Trace.WriteLine("MaxSessions = " + serviceThrottle.MaxConcurrentSessions); Trace.WriteLine("MaxInstances = " + serviceThrottle.MaxConcurrentInstances); } } 则输出结果为: MaxConcurrentCalls = 12 MaxSessions = 56 MaxInstances = 34 |