实现此目的的一种方法是使用一个 ServiceBehavior,它添加一个实现 IInstanceContextInitializer 的实例。
我的实现如下所示:
public class PerOperationThrottle: IInstanceContextInitializer
{
static MemoryCache cache = new MemoryCache("foo", null);
public void Initialize(InstanceContext instanceContext, Message message)
{
RemoteEndpointMessageProperty ep = message.Properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
// which action do we want to throttle
if (message.Headers.Action.EndsWith("register") &&
ep != null &&
ep.Address != null)
{
// get the IP address
var item = cache[ep.Address];
if (item == null)
{
// not found, so init
cache.Add(
ep.Address,
new Counter { Count = 0 },
new CacheItemPolicy
{
SlidingExpiration = new TimeSpan(0, 1, 0) // 1 minute
});
}
else
{
// how many calls?
var count = (Counter)item;
if (count.Count > 5)
{
instanceContext.Abort();
// not sure if this the best way to break
throw new Exception("throttle");
}
// add one call
count.Count++;
}
}
}
}
我使用了一个有点幼稚的 MemoryCache 实现,它为我的自定义 Counter 类的每个 IP 地址保存一个实例:
public class Counter
{
public int Count;
}
要将PerOperationThrottle 的实例连接到服务,我有一个帮助类,它结合了IServiceBehavior 和IEndpointBehavior 的实现:
public class PerOperationThrottleBehaviorAttribute : Attribute, IServiceBehavior,IEndpointBehavior
{
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach(var ep in serviceDescription.Endpoints)
{
// add the EndpointBehavior
ep.EndpointBehaviors.Add(this);
}
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
// our PerOperationThrottle gets created and wired
endpointDispatcher.
DispatchRuntime.
InstanceContextInitializers.
Add(new PerOperationThrottle());
}
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
}
空方法属于接口,但不需要任何实现。不过请务必删除throw new NotImplementedException();。
最后我们用自定义属性PerOperationThrottleBehavior注解Service实现类
[PerOperationThrottleBehavior]
public class Service1 : IService1
{
public string register(int value)
{
return string.Format("You entered: {0}", value);
}
}
如果register 操作在一分钟内被调用超过 5 次,服务会抛出异常。