csredis icon indicating copy to clipboard operation
csredis copied to clipboard

连接池是否可以增加一个释放机制,有一个poolMinSize。下面我实现的释放方法,是否有问题。

Open youweimao opened this issue 4 years ago • 2 comments

在连接池对象构造的方法中增加 //定时释放连接池对象 StartReleasePoolService();

  /// <summary>
    /// 增加过期回收
    /// </summary>
    private void StartReleasePoolService()
    {
        new Thread(() =>
        {
            
            for (int i = _freeObjects.Count; i > 0; i--)
            {
                Console.WriteLine($"释放。。。{i}/{_freeObjects.Count}");
                try
                {
                    if (_freeObjects.Count <= this.Policy.PoolMinSize)
                        break;

                    bool tryGet = _freeObjects.TryPop(out var obj);
                    if (tryGet
                    && obj != null
                    //&& Policy.IdleTimeout > TimeSpan.Zero(如果开启该条件,其他地方会报错)
                    && DateTime.Now.Subtract(obj.LastReturnTime) > TimeSpan.FromMinutes(this.Policy.PoolReleaseInterval))
                    {
                        this.Policy.OnDestroy(obj.Value);
                    }
                    else
                    {
                        Return(obj);
                    }
                }
                catch (Exception ex){
                    Console.WriteLine("释放发生错误:"+ex.Message);
                }
            }

     
            for (var a = 0; a < _allObjects.Count; a++)
            {
                if (_allObjects.Count <= this.Policy.PoolMinSize)
                    break;

                if (_allObjects[a] != null
                   //&& Policy.IdleTimeout > TimeSpan.Zero
                   && DateTime.Now.Subtract(_allObjects[a].LastReturnTime) > TimeSpan.FromMinutes(this.Policy.PoolReleaseInterval))
                {
                    Policy.OnDestroy(_allObjects[a].Value);
                    try { (_allObjects[a].Value as IDisposable)?.Dispose(); } catch { }
                    try { lock (_allObjectsLock) _allObjects.Remove(_allObjects[a]); } catch { }
                }
            }

            Thread.CurrentThread.Join(TimeSpan.FromMinutes(this.Policy.PoolReleaseInterval + 1));//避免释放不掉。
            StartReleasePoolService();
        }).Start();
    }

youweimao avatar Jan 30 '21 07:01 youweimao

如果连接释放掉了,会不会影响订阅?如果影响,该怎么处理呢?

youweimao avatar Jan 30 '21 07:01 youweimao

定时释放可以在服务器设置,redis-server 有对应的设置。

2881099 avatar Jan 30 '21 08:01 2881099