WCF限流詳細配置介紹
WCF框架熟練應用需要我們在實踐中去不斷的鞏固,才能真正掌握這一框架的應用技巧。WCF限流不是直接的實例管理技術,他允許開發者限制客戶端的連接數已經服務器負荷。#t#
使用限流技術以后,一旦超出配置的設置值,WCF就會自動的將等待處理的調用放入隊列中,然后再依次從隊列中取出,如果客戶端等待超時,那么客戶端會獲得一個TimeoutException異常。每個服務類型都可以使用WCf限流技術。
WCF限流配置參數
并發會話最大數:針對TCP,IPC等能保持傳輸層連接的會話的服務綁定的獨立客戶端最大數,也就是能保持會話的客戶端的最大連接數。對于Http等無連接的服務是無效的,默認為10
并發調用最大數:指所有服務實例中讀取正在執行的調用總數
并發實例最大數:表示存活的并發上下文總數。默認是無限的。
配置WCF限流
- < behaviors>
- < serviceBehaviors>
- < behavior name =
"ThrottledBehavior">- < serviceThrottling
- maxConcurrentCalls ="12"
- maxConcurrentSessions ="34"
- maxConcurrentInstances ="2"
- />
- < /behavior>
- < /serviceBehaviors>
- < /behaviors>
在服務端讀取WCF限流參數
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);
編程配置WCF限流
宿主進程可以以編程方式配置限流,但是要在打開宿主之前執行
- ServiceHost host =
new ServiceHost(typeof(MyService));- //Make sure there is no
throttle in the config file- ServiceThrottlingBehavior
throttle = host.Description.
Behaviors.Find< Service
ThrottlingBehavior>();- if(throttle == null)
- {
- throttle = new Service
ThrottlingBehavior();- throttle.MaxConcurrentCalls = 12;
- throttle.MaxConcurrentSessions = 34;
- throttle.MaxConcurrentInstances = 2;
- host.Description.
Behaviors.Add(throttle);- }
- host.Open();
綁定中的WCF限流連接
在使用TCP和IPC綁定的時候我們也可以在綁定中為一個特定的終結點配置最大連接數。
- < netTcpBinding>
- < binding name="TCPThrottle"
maxConnections="25">- < /binding>
- < /netTcpBinding>
maxConnections的默認值為10,如果綁定限流與服務行為的WCF限流都設置了最大連接值,WCF選擇其中較小的一個