Exemplo n.º 1
0
 public static async Task <ModelWrapper> PullModel()
 {
     if (!modelPool.TryDequeue(out var model))
     {
         ConnectionWrapper conn = null;
         foreach (var item in connectionList)
         {
             if (item.Increment() <= 15)
             {
                 conn = item;
                 break;
             }
             else
             {
                 item.Decrement();
             }
         }
         if (conn == null && Interlocked.Increment(ref connectionCount) <= rabbitHost.MaxPoolSize)
         {
             conn = new ConnectionWrapper()
             {
                 Connection = _Factory.CreateConnection(rabbitHost.EndPoints)
             };
             conn.Connection.ConnectionShutdown += (obj, args) =>
             {
                 conn.Connection = _Factory.CreateConnection(rabbitHost.EndPoints);
                 conn.Reset();
             };
             connectionList.Add(conn);
         }
         if (conn != null)
         {
             model = new ModelWrapper()
             {
                 Connection = conn, Model = conn.Connection.CreateModel()
             };
             model.Model.ConfirmSelect();
         }
         else
         {
             Interlocked.Decrement(ref connectionCount);
         }
     }
     if (model == null)
     {
         var taskSource = new TaskCompletionSource <ModelWrapper>();
         modelTaskPool.Enqueue(taskSource);
         var cancelSource = new CancellationTokenSource(3000);
         cancelSource.Token.Register(() =>
         {
             taskSource.SetException(new Exception("get rabbitmq's model timeout"));
         });
         model = await taskSource.Task;
     }
     if (model.Model.IsClosed)
     {
         model.Connection.Decrement();
         model = await PullModel();
     }
     return(model);
 }