예제 #1
0
        public ConnectionMultiplexer2 GetConnection()
        {
            ConnectionMultiplexer2 conn = null;

            if (FreeConnections.Count > 0)
            {
                lock (_lock)
                    if (FreeConnections.Count > 0)
                    {
                        conn = FreeConnections.Dequeue();
                    }
            }
            if (conn == null && AllConnections.Count < MaxPoolSize)
            {
                lock (_lock)
                    if (AllConnections.Count < MaxPoolSize)
                    {
                        conn = new ConnectionMultiplexer2();
                        AllConnections.Add(conn);
                    }
                if (conn != null)
                {
                    conn.Pool     = this;
                    conn.ThreadId = Thread.CurrentThread.ManagedThreadId;
                }
            }
            if (conn == null)
            {
                ManualResetEvent wait = new ManualResetEvent(false);
                lock (_lock_GetConnectionQueue)
                    GetConnectionQueue.Enqueue(wait);
                if (wait.WaitOne(TimeSpan.FromSeconds(10)))
                {
                    return(GetConnection());
                }
                throw new Exception("GetConnection 连接池获取超时10秒");
            }
            conn.ThreadId   = Thread.CurrentThread.ManagedThreadId;
            conn.LastActive = DateTime.Now;
            Interlocked.Increment(ref conn.UseSum);
            try {
                if (conn.Database == null || !conn.Database.IsConnected("test"))
                {
                    conn.Connection = ConnectionMultiplexer.Connect(ConnectionString);
                    conn.Database   = conn.Connection.GetDatabase();
                }
            } catch (Exception ex) {
                throw new Exception("GetConnection/GetDatabase 出错", ex);
            }
            return(conn);
        }
예제 #2
0
        public void ReleaseConnection(ConnectionMultiplexer2 conn)
        {
            lock (_lock)
                FreeConnections.Enqueue(conn);

            if (GetConnectionQueue.Count > 0)
            {
                ManualResetEvent wait = null;
                lock (_lock_GetConnectionQueue)
                    if (GetConnectionQueue.Count > 0)
                    {
                        wait = GetConnectionQueue.Dequeue();
                    }
                if (wait != null)
                {
                    wait.Set();
                }
            }
        }