管理和限制API会话的数量
本文关键字:会话 API 管理 | 更新日期: 2023-09-27 18:29:33
我使用的是一个WSDLneneneba API,它在任何时候都限制为100个会话。我使用的是C#,所以这意味着在我的应用程序中,我只能有100个WSSession类实例,否则API将拒绝调用。
我能采取的最好的方法是什么?我在一个大型应用程序中工作,它可以很容易地达到100个会话的限制。我不想在达到会话限制时抛出错误,相反,我宁愿在会话可用之前进行阻止。
您可以通过一个服务路由所有远程调用,在该服务中,您可以记录调用发生时执行的操作数量。
您可以使用Semaphore来控制给定块上的并发性。
假设您为外部Web服务创建了一个代理服务,则可以创建这样的服务来处理所有调用。我还假设您正在使用控制反转,因此您需要确保只有该服务的一个实例处理所有调用。
有其他选择;
- 将信号量移出并使其成为单例
- 或者通过给信号量一个名称
服务:
public class PooledService
{
private readonly Semaphore _semaphore;
private readonly WebService _service;
public PooledService(WebService service, int max)
{
_semaphore = new Semaphore(max, max);
_service = service;
}
public R Execute<R>(Func<WebService, R> expression)
{
//will block if concurrency is at maximum, waiting up to 5 seconds
//if you want to wait forever, then just call _semaphore.WaitOne();
if (!_semaphore.WaitOne(5000))
throw new Exception("Timed Out");
try
{
return expression(_service);
}
finally
{
_semaphore.Release();
}
}
public void Execute(Action<WebService> expression)
{
//will block if concurrency is at maximum, waiting up to 5 seconds
//if you want to wait forever, then just call _semaphore.WaitOne();
if (!_semaphore.WaitOne(5000))
throw new Exception("Timed Out");
try
{
expression(_service);
}
finally
{
_semaphore.Release();
}
}
}
你可以这样使用它;
var service = new PooledService(new WebService(), 100); //maximum of 100 concurrent calls
var response = service.Execute(s => s.SomeRemoteCall(...));