StackExchange.Redis TimeOut 记录

前言

最近在用.Net Core 做业务模块时,发现经常会出现TimeOut 超时的情况。然后看了官方的解释,说2.0版本之后维护了一个专用的线程池。我就打算阅读源码,看一下这个线程池的实现。

源码

StackExchange.Redis源码 中可以看到,其中维护了一个名为:DedicatedThreadPoolPipeScheduler 的线程池,此线程池引用了一个使用并不多的第三方开源库Pipelines.Sockets.Unofficial。这个库给我的第一感觉就是,用的很少,估计有坑。

我们先来看一下这个 DedicatedThreadPoolpipeScheduler 的实现:

/// <summary>
    /// An implementation of a pipe-scheduler that uses a dedicated pool of threads, deferring to
    /// the thread-pool if that becomes too backlogged
    /// </summary>
    public sealed class DedicatedThreadPoolPipeScheduler : PipeScheduler, IDisposable
    {
        /// <summary>
        /// Reusable shared scheduler instance
        /// </summary>
        public static DedicatedThreadPoolPipeScheduler Default => StaticContext.Instance;

        private static class StaticContext
        {   // locating here rather than as a static field on DedicatedThreadPoolPipeScheduler so that it isn't instantiated too eagerly
            internal static readonly DedicatedThreadPoolPipeScheduler Instance = new DedicatedThreadPoolPipeScheduler(nameof(Default));
        }

        /// <summary>
        /// The name of the pool
        /// </summary>
        public override string ToString() => Name;

        /// <summary>
        /// The number of workers associated with this pool
        /// </summary>
        public int WorkerCount { get; }

        private int UseThreadPoolQueueLength { get; }

        private ThreadPriority Priority { get; }

        private string Name { get; }

        /// <summary>
        /// Create a new dedicated thread-pool
        /// </summary>
        public DedicatedThreadPoolPipeScheduler(string name = null, int workerCount = 5, int useThreadPoolQueueLength = 10,
            ThreadPriority priority = ThreadPriority.Normal)
        {
            if (workerCount < 0) throw new ArgumentNullException(nameof(workerCount));

            WorkerCount = workerCount;
            UseThreadPoolQueueLength = useThreadPoolQueueLength;
            if (string.IsNullOrWhiteSpace(name)) name = GetType().Name;
            Name = name.Trim();
            Priority = priority;
            for (int i = 0; i < workerCount; i++)
            {
                StartWorker(i);
            }
        }

        private long _totalServicedByQueue, _totalServicedByPool;

        /// <summary>
        /// The total number of operations serviced by the queue
        /// </summary>
        public long TotalServicedByQueue => Volatile.Read(ref _totalServicedByQueue);

        /// <summary>
        /// The total number of operations that could not be serviced by the queue, but which were sent to the thread-pool instead
        /// </summary>
        public long TotalServicedByPool => Volatile.Read(ref _totalServicedByPool);

        private readonly struct WorkItem
        {
            public readonly Action<object> Action;
            public readonly object State;
            public WorkItem(Action<object> action, object state)
            {
                Action = action;
                State = state;
            }
        }

        private volatile bool _disposed;

        private readonly Queue<WorkItem> _queue = new Queue<WorkItem>();
        private void StartWorker(int id)
        {
            var thread = new Thread(ThreadRunWorkLoop)
            {
                Name = $"{Name}:{id}",
                Priority = Priority,
                IsBackground = true
            };
            thread.Start(this);
            Helpers.Incr(Counter.ThreadPoolWorkerStarted);
        }

        /// <summary>
        /// Requests <paramref name="action"/> to be run on scheduler with <paramref name="state"/> being passed in
        /// </summary>
        public override void Schedule(Action<object> action, object state)
        {
            if (action == null) return; // nothing to do
            int queueLength;
            lock (_queue)
            {
                _queue.Enqueue(new WorkItem(action, state));
                if (_availableCount != 0)
                {
                    Monitor.Pulse(_queue); // wake up someone
                }
                queueLength = _queue.Count;
            }

            if (_disposed || queueLength > UseThreadPoolQueueLength)
            {
                Helpers.Incr(Counter.ThreadPoolPushedToMainThreadPool);
                System.Threading.ThreadPool.QueueUserWorkItem(ThreadPoolRunSingleItem, this);
            }
            else
            {
                Helpers.Incr(Counter.ThreadPoolScheduled);
            }
        }

        private static readonly ParameterizedThreadStart ThreadRunWorkLoop = state => ((DedicatedThreadPoolPipeScheduler)state).RunWorkLoop();
        private static readonly WaitCallback ThreadPoolRunSingleItem = state => ((DedicatedThreadPoolPipeScheduler)state).RunSingleItem();

        private int _availableCount;
        /// <summary>
        /// The number of workers currently actively engaged in work
        /// </summary>
        public int AvailableCount => Thread.VolatileRead(ref _availableCount);

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private void Execute(Action<object> action, object state)
        {
            try
            {
                action(state);
                Helpers.Incr(Counter.ThreadPoolExecuted);
                Helpers.Incr(action == SocketAwaitableEventArgs.InvokeStateAsAction ? ((Action)state).Method : action.Method);
            }
            catch (Exception ex)
            {
                Helpers.DebugLog(Name, ex.Message);
            }
        }

        private void RunSingleItem()
        {
            WorkItem next;
            lock (_queue)
            {
                if (_queue.Count == 0) return;
                next = _queue.Dequeue();
            }
            Interlocked.Increment(ref _totalServicedByPool);
            Execute(next.Action, next.State);
        }
        private void RunWorkLoop()
        {
            while (true)
            {
                WorkItem next;
                lock (_queue)
                {
                    while (_queue.Count == 0)
                    {
                        if (_disposed) break;
                        _availableCount++;
                        Monitor.Wait(_queue);
                        _availableCount--;
                    }
                    if (_queue.Count == 0)
                    {
                        if (_disposed) break;
                        else continue;
                    }
                    next = _queue.Dequeue();
                }
                Interlocked.Increment(ref _totalServicedByQueue);
                Execute(next.Action, next.State);
            }
        }
        /// <summary>
        /// Release the threads associated with this pool; if additional work is requested, it will
        /// be sent to the main thread-pool
        /// </summary>
        public void Dispose()
        {
            _disposed = true;
            lock (_queue)
            {
                Monitor.PulseAll(_queue);
            }
        }
    }

可以看到内部维护了一个任务队列,默认工作线程为5个。最重要的一段是这里:

    /// <summary>
        /// Requests <paramref name="action"/> to be run on scheduler with <paramref name="state"/> being passed in
        /// </summary>
        public override void Schedule(Action<object> action, object state)
        {
            if (action == null) return; // nothing to do
            int queueLength;
            lock (_queue)
            {
                _queue.Enqueue(new WorkItem(action, state));
                if (_availableCount != 0)
                {
                    Monitor.Pulse(_queue); // wake up someone
                }
                queueLength = _queue.Count;
            }

            if (_disposed || queueLength > UseThreadPoolQueueLength)
            {
                Helpers.Incr(Counter.ThreadPoolPushedToMainThreadPool);
                System.Threading.ThreadPool.QueueUserWorkItem(ThreadPoolRunSingleItem, this);
            }
            else
            {
                Helpers.Incr(Counter.ThreadPoolScheduled);
            }
        }

当任务队列长度超过 UseThreadPoolQueueLength (默认为10)或者这个专用线程池被释放而又存在没有处理完的任务时,就会使用.Net全局线程池来帮助处理任务。
另外的问题就是,这个默认线程池工作线程数量,在StackExchange.Redis中是不可配置的,默认就是5。所以如果使用单实例模型来使用这个Redis库时,一旦并发数高就会出现超时的任务,根据现有资料可以看到

For these .NET-provided global thread pools: once the number of existing (busy) threads hits the "minimum" number of threads, the ThreadPool will throttle the rate at which is injects new threads to one thread per 500 milliseconds. This means that if your system gets a burst of work needing an IOCP thread, it will process that work very quickly. However, if the burst of work is more than the configured "Minimum" setting, there will be some delay in processing some of the work as the ThreadPool waits for one of two things to happen 1. An existing thread becomes free to process the work 2. No existing thread becomes free for 500ms, so a new thread is created.
Basically, if you're hitting the global thread pool (rather than the dedicated StackExchange.Redis thread-pool) it means that when the number of Busy threads is greater than Min threads, you are likely paying a 500ms delay before network traffic is processed by the application. Also, it is important to note that when an existing thread stays idle for longer than 15 seconds (based on what I remember), it will be cleaned up and this cycle of growth and shrinkage can repeat.

.Net全局线程池在超过最小线程数时,要花费500ms 创建一个线程,当线程闲时超过15秒时就会被回收,是一个动态伸缩的线程池。

那么总结一下就是:

  1. StackExchange.Redis维护了一个专有线程池,但是在线程数超过5,且并发数超过10(每个任务处理的非常慢的极端情况)就会使用.Net 全局线程池。
  2. StackExchange.Redis无法配置这个工作线程数。
  3. 当并发过多,且全局线程池的Minimum 很小时,就会出现超时TimeOut 的情况。

解决方案:

  1. 创建多个ConnectionMultiplexer 实例(每个实例有5个专用工作线程),理论上粗略计算可以处理N510个并发。
  2. 自己编译源码修改工作线程数。
  3. System.Threading.ThreadPool.SetMinThreads(200, 200); //根据并发估算,设置一下全局线程池的最小值。

但是以上的解决方案,感觉都不好。最好的方式应该就是,自己写一个Redis的客户端,然后实现一个能够动态扩容和收缩的线程池。StackExchange.Redis代码结构看着也不够清晰。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,106评论 0 10
  • 北京 第一教堂 婚礼进行时 热热闹闹的氛围,伴随着美丽新娘的到来,掌声响起。 慕珂馨被慕父引着,走向她余生的眷...
    囖_25ba阅读 163评论 0 1
  • 抓住终端色,提纲挈领!表达结构规律,主观塑造!强调瞬间感受,笔随意走!有的放矢,一气呵成!
    夜书童阅读 128评论 0 0