限流
限流(Throttling)并非直接的实例管理技术,它允许开发者限制客户端连接数以及服务的负荷。
限流项
WCF允许开发者控制下列的消费参数:
- 并发会话最大数
- 并发调用最大数
配置限流
通常,限流是管理员在配置文件中配置的。它允许我们能够在不同时间或者横跨不同的部署站点限制相同的服务代码。
同样宿主能够基于某种运行时决策,以编程方式配置限流。
web.config配置限流
限流的配置属性局部视图:
编程配置限流
selfhost.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true });
//添加限流
ServiceThrottlingBehavior throttle;
throttle = selfhost.Description.Behaviors.Find<ServiceThrottlingBehavior>();
if (throttle == null)
{
throttle = new ServiceThrottlingBehavior()
{
MaxConcurrentCalls = 10,
MaxConcurrentSessions = 30,
MaxConcurrentInstances = 60
};
selfhost.Description.Behaviors.Add(throttle);
}
获取服务限流
/// <summary>
/// 获取服务限流对象 <see cref="ServiceThrottle"/>
/// </summary>
/// <returns></returns>
public ServiceThrottle GetServiceHostThrottle()
{
ChannelDispatcher dispatcher = OperationContext.Current.
Host.ChannelDispatchers[0] as ChannelDispatcher;
return dispatcher.ServiceThrottle;
}
绑定中的限流数量
在使用TCP和命名管道绑定时,我们也可以在绑定中为一个特定的终结点配置最大连接数。NetTcpBinding 和 NetNamedPipeBinding中都有一个 MaxConnections属性。