本文介绍了如何限制HttpWebRequest的数量每秒向Web服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用的HttpWebRequest迈向一个应用服务器在进行并行请求时实施限制的机制(每秒请求数)。我的C#应用​​程序必须发出每秒不超过80个请求发送到远程服务器。该限制由远程服务管理员不作为硬性限制,但作为我的平台与他们之间的SLA强加的。

I need to implement a throttling mechanism (requests per second) when using HttpWebRequest for making parallel requests towards one application server. My C# app must issue no more than 80 requests per second to a remote server. The limit is imposed by the remote service admins not as a hard limit but as "SLA" between my platform and theirs.

我如何控制每秒请求数使用HttpWebRequest的?

How can I control the number of requests per second when using HttpWebRequest?

推荐答案

我有同样的问题,但没有找到一个现成的解决方案,所以我做了一个,在这里它是。这个想法是使用 BlockingCollection< T> 添加需要处理和使用无功扩展与速率受限的处理器,订阅项目

I had the same problem and couldn't find a ready solution so I made one, and here it is. The idea is to use a BlockingCollection<T> to add items that need processing and use Reactive Extensions to subscribe with a rate-limited processor.

油门类的

public static class BlockingCollectionExtensions
{
    // TODO: devise a way to avoid problems if collection gets too big (produced faster than consumed)
    public static IObservable<T> AsRateLimitedObservable<T>(this BlockingCollection<T> sequence, int items, TimeSpan timePeriod, CancellationToken producerToken)
    {
        Subject<T> subject = new Subject<T>();

        // this is a dummyToken just so we can recreate the TokenSource
        // which we will pass the proxy class so it can cancel the task
        // on disposal
        CancellationToken dummyToken = new CancellationToken();
        CancellationTokenSource tokenSource = CancellationTokenSource.CreateLinkedTokenSource(producerToken, dummyToken);

        var consumingTask = new Task(() =>
        {
            using (var throttle = new Throttle(items, timePeriod))
            {
                while (!sequence.IsCompleted)
                {
                    try
                    {
                        T item = sequence.Take(producerToken);
                        throttle.WaitToProceed();
                        try
                        {
                            subject.OnNext(item);
                        }
                        catch (Exception ex)
                        {
                            subject.OnError(ex);
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        break;
                    }
                }
                subject.OnCompleted();
            }
        }, TaskCreationOptions.LongRunning);

        return new TaskAwareObservable<T>(subject, consumingTask, tokenSource);
    }

    private class TaskAwareObservable<T> : IObservable<T>, IDisposable
    {
        private readonly Task task;
        private readonly Subject<T> subject;
        private readonly CancellationTokenSource taskCancellationTokenSource;

        public TaskAwareObservable(Subject<T> subject, Task task, CancellationTokenSource tokenSource)
        {
            this.task = task;
            this.subject = subject;
            this.taskCancellationTokenSource = tokenSource;
        }

        public IDisposable Subscribe(IObserver<T> observer)
        {
            var disposable = subject.Subscribe(observer);
            if (task.Status == TaskStatus.Created)
                task.Start();
            return disposable;
        }

        public void Dispose()
        {
            // cancel consumption and wait task to finish
            taskCancellationTokenSource.Cancel();
            task.Wait();

            // dispose tokenSource and task
            taskCancellationTokenSource.Dispose();
            task.Dispose();

            // dispose subject
            subject.Dispose();
        }
    }
}



单元测试:

Unit test:

class BlockCollectionExtensionsTest
{
    [Fact]
    public void AsRateLimitedObservable()
    {
        const int maxItems = 1; // fix this to 1 to ease testing
        TimeSpan during = TimeSpan.FromSeconds(1);

        // populate collection
        int[] items = new[] { 1, 2, 3, 4 };
        BlockingCollection<int> collection = new BlockingCollection<int>();
        foreach (var i in items) collection.Add(i);
        collection.CompleteAdding();

        IObservable<int> observable = collection.AsRateLimitedObservable(maxItems, during, CancellationToken.None);
        BlockingCollection<int> processedItems = new BlockingCollection<int>();
        ManualResetEvent completed = new ManualResetEvent(false);
        DateTime last = DateTime.UtcNow;
        observable
            // this is so we'll receive exceptions
            .ObserveOn(new SynchronizationContext()) 
            .Subscribe(item =>
                {
                    if (item == 1)
                        last = DateTime.UtcNow;
                    else
                    {
                        TimeSpan diff = (DateTime.UtcNow - last);
                        last = DateTime.UtcNow;

                        Assert.InRange(diff.TotalMilliseconds,
                            during.TotalMilliseconds - 30,
                            during.TotalMilliseconds + 30);
                    }
                    processedItems.Add(item);
                },
                () => completed.Set()
            );
        completed.WaitOne();
        Assert.Equal(items, processedItems, new CollectionEqualityComparer<int>());
    }
}

这篇关于如何限制HttpWebRequest的数量每秒向Web服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 21:56