WebApi HttpClient每个请求每个池中的新连接

时间:2014-11-22 10:32:52

标签: asp.net-web-api httpclient

就我而言,我通过HttpClient向服务器端发出Web请求。但每次,连接池中都会有一个新连接。该程序仅使用一个连接字符串。新连接上升得太快,然后超过最大池大小100.我必须解决有关数据库连接池和IIS的问题。

sqlserver数据库连接字符串:

  <connectionStrings>
    <add name="WERP2ConnectionString" connectionString="Data Source=localhost;Initial Catalog=WERP2-1108;User ID=sa;Password=sasa;Connect Timeout=15;Encrypt=False;"/>
  </connectionStrings>

客户端程序:

static void Main(string[] args)
{
    for (int i = 0; i < 5; i++)
    {
        Console.WriteLine("api test: {0}", i);
        ApiTest();   //to mimic the 5 different users make the api request.
    }
    Console.ReadLine();
}


private static void ApiTest()
{
    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost/StressApi/");
        client.DefaultRequestHeaders.Accept.Add(
            new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        var response = client.GetAsync("api/order/GetOrder").Result;
        if (response.IsSuccessStatusCode)
        {
            var message = response.Content.ReadAsStringAsync().Result;
            if (!string.IsNullOrEmpty(message))
            {
                Console.WriteLine(message);
            }
        }
        else
        {
            Console.WriteLine("Error Code" +
            response.StatusCode + " : Message - " + response.ReasonPhrase);
        }
        //Console.ReadLine();
    }
}

WebApi控制器:

public class OrderController : ApiController
{
    [HttpGet]
    public HttpResponseMessage GetOrder()
    {
        OrderModel model = new OrderModel();
        var entity = model.GetByID();
        HttpResponseMessage response = Request.CreateResponse<OrderEntity>(HttpStatusCode.OK, entity);

        return response;
    }
}

public class OrderEntity
{
    public int ID { get; set; }
    public string OrderCode { get; set; }
    public int OrderType { get; set; }
}

public class OrderModel
{
    public OrderEntity GetByID()
    {
        OrderEntity entity = new OrderEntity();

        string sql = @"select * from salorder where id=97";
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WERP2ConnectionString"].ToString()))
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            // don't forget to actually open the connection before using it
            conn.Open();
            try
            {
                using (SqlDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                {
                    while (dataReader.Read())
                    {
                        // do something
                        Console.WriteLine(dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + " - " + dataReader.GetValue(2));
                        entity.ID = int.Parse(dataReader.GetValue(0).ToString());
                        entity.OrderCode = dataReader.GetValue(1).ToString();
                        entity.OrderType = int.Parse(dataReader.GetValue(2).ToString());
                        //dataReader
                    }
                }
            }
            finally
            {
                //SqlConnection.ClearPool(conn);
            }
        }
        return entity;
    }
}

每个sql查询都会在sqlserver中创建一个进程,我们可以在SQL SERVER Activity Monitor中找到它们,并且有5条记录,因为我重复了5次查询。

enter image description here

如果我们使用SP_WHO命令,我们也可以验证5个进程记录,它们处于睡眠 AWAITTING COMMAND状态。

enter image description here

我很困惑,我怎么能避免这种连接泄漏问题。虽然我每次都进行相同的sql查询,但仍然会重新生成新的连接。我已经测试过这些连接将在6分20秒左右回收。当然,我可以重置IIS或使应用程序池回收以释放它们。但这绝对不能在线上系统接受。请有人可以提出任何建议吗?感谢。

顺便说一下,编程是使用.NET Framework 4.0,IIS7和SQLSERVER2008 R2运行的。

1 个答案:

答案 0 :(得分:1)

HttpClient将为每个请求打开一个新套接字。因此,建议使用此单个实例。

有关更多信息,请转到以下链接

https://www.codeproject.com/Articles/1194406/Using-HttpClient-As-It-Was-Intended-Because-You-re