我在三台不同的计算机上平衡了WCF服务负载。
假设这些服务可以处理类型 A , B 和 C 的请求。处理 A 或 B 没有限制。但是,我们一次只能处理5个 C 类型的请求,因此如果第6个类型为 C 的请求进入,则必须等到其中一个先前的请求完成。
如何确保在所有三台计算机上只处理5个 C 类型的请求?
答案 0 :(得分:8)
听起来你需要一个跨机器信号量,你可以使用像memcached这样的分布式缓存解决方案实现一个。或者,您可以在一台机器上运行另一个WCF服务,该服务器管理负载均衡服务的信号量。
所以新服务可能看起来像这样:
[ServiceContract]
public interface ISemaphorService
{
[OperationContract]
void Acquire();
[OperationContract]
void Release();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class SemaphoreService
{
private readonly static Semaphore Pool = new Semaphore(5, 5);
public void Acquire()
{
Pool.WaitOne();
}
public void Release()
{
Pool.Release();
}
}
在真实世界的应用程序中,您可能希望在配置或其他内容中配置信号量的数量并放入一些超时并设置机制以确保及时发布信号量和/或客户端崩溃时:
// on the client side (service C)
var client = new SemaphoreServiceClient();
try
{
// acquire the semaphore before processing the request
client.Acquire();
// process request
...
}
finally
{
// always remember the release the semaphore
client.Release();
}