Home Database Mysql Tutorial SqlConnection 的连接池机制解析

SqlConnection 的连接池机制解析

Jun 07, 2016 pm 05:48 PM
connection pool

提供一篇关于sqlconnection连接池详细,有需要的朋友参考一下。

物理连接建立时,需要做和服务器握手,解析连接字符串,授权,约束的检查等等操作,而物理连接建立后,这些操作就不会去做了。这些操作是需要一定的时间的。所以很多人喜欢用一个静态对象存储 SqlConnection 来始终保持物理连接,但采用静态对象时,多线程访问会带来一些问题,实际上,我们完全不需要这么做,因为 SqlConnection 默认打开了连接池功能,当程序 执行  SqlConnection.Close 后,物理连接并不会被立即释放,所以这才出现当循环执行 Open操作时,执行时间几乎为0.

下面我们先看一下不打开连接池时,循环执行 SqlConnection.Open 的耗时

 

 代码如下 复制代码

       public static void OpenWithoutPooling()
        {
            string connectionString =
                "Data Source=192.168.10.2; Initial Catalog=News; Integrated Security=True;Pooling=False;";

            Stopwatch sw = new Stopwatch();

            sw.Start();
            using (SqlConnection conn =
                new SqlConnection(connectionString))
            {
                conn.Open();
            }

            sw.Stop();
            Console.WriteLine("Without Pooling, first connection elaed {0} ms", sw.ElapsedMilliseconds);

            sw.Reset();

            sw.Start();

            for (int i = 0; i             {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();
                }
            }

            sw.Stop();
            Console.WriteLine("Without Pooling, average connection elapsed {0} ms", sw.ElapsedMilliseconds / 100);
        }

 

SqlConnection 默认是打开连接池的,如果要强制关闭,我们需要在连接字符串中加入 Pooling=False

调用程序如下:

 代码如下 复制代码
                Test.SqlConnectionTest.OpenWithoutPooling();
                Console.WriteLine("Waiting for 10s");
                System.Threading.Thread.Sleep(10 * 1000);
                Test.SqlConnectionTest.OpenWithoutPooling();
                Console.WriteLine("Waiting for 600s");
                System.Threading.Thread.Sleep(600 * 1000);
                Test.SqlConnectionTest.OpenWithoutPooling();

下面是测试结果 

Without Pooling, first connection elapsed 13 ms
Without Pooling, average connection elapsed 5 ms
Wating for 10s
Without Pooling, first connection elapsed 6 ms
Without Pooling, average connection elapsed 4 ms
Wating for 600s
Without Pooling, first connection elapsed 7 ms
Without Pooling, average connection elapsed 4 ms

从这个测试结果看,关闭连接池后,平均每次连接大概要耗时4个毫秒左右,这个就是建立物理连接的平均耗时。

 

下面再看默认情况下的测试代码

      

 代码如下 复制代码

  public static void OpenWithPooling()
        {
            string connectionString =
                "Data Source=192.168.10.2; Initial Catalog=News; Integrated Security=True;";
           
            Stopwatch sw = new Stopwatch();

            sw.Start();
            using (SqlConnection conn =
                new SqlConnection(connectionString))
            {
                conn.Open();
            }

            sw.Stop();
            Console.WriteLine("With Pooling, first connection elapsed {0} ms", sw.ElapsedMilliseconds);

            sw.Reset();

            sw.Start();

            for (int i = 0; i             {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();
                }
            }

            sw.Stop();
            Console.WriteLine("With Pooling, average connection elapsed {0} ms", sw.ElapsedMilliseconds / 100);
        }


调用代码

 

                Test.SqlConnectionTest.OpenWithPooling();
                Console.WriteLine("Waiting for 10s");
                System.Threading.Thread.Sleep(10 * 1000);
                Test.SqlConnectionTest.OpenWithPooling();
                Console.WriteLine("Waiting for 600s");
                System.Threading.Thread.Sleep(600 * 1000);
                Test.SqlConnectionTest.OpenWithPooling();
测试结果

With Pooling, first connection elapsed 119 ms
With Pooling, average connection elapsed 0 ms
Waiting for 10s
With Pooling, first connection elapsed 0 ms
With Pooling, average connection elapsed 0 ms
Waiting for 600s
With Pooling, first connection elapsed 6 ms
With Pooling, average connection elapsed 0 ms


这个测试结果看,第一次耗时是119ms,这是因为我在测试代码中,首先运行的是这个测试过程,119 ms 是程序第一次启动时的首次连接耗时,这个耗时可能不光包括连接的时间,还有 ado.net 自己初始化的用时,所以这个用时可以不管。10秒以后在执行这个测试过程,首次执行的时间变成了0ms,这说明连接池机制发生了作用,SqlConnection Close 后,物理连接并没有被关闭,所以10秒后再执行,连接几乎没有用时间。

但我们发现一个有趣的现象,10分钟后,首次连接时间变成了6ms,这个和前面不打开连接池的测试用时几乎一样,也就是说10分钟后,物理连接被关闭了,又重新打开了一个物理连接。这个现象是因为连接池有个超时时间,默认情况下应该在5-10分钟之间,如果在此期间没有任何的连接操作,物理连接就会被关闭。那么我们有没有办法始终保持物理连接呢?方法是有的。

连接池设置中有一个最小连接池大小,默认为0,我们把它设置为大于0的值就可以保持若干物理连接始终不释放了。看代码

 

 代码如下 复制代码

 

        public static void OpenWithPooling(int minPoolSize)
        {
            string connectionString =
                string.Format("Data Source=192.168.10.2; Initial Catalog=News; Integrated Security=True;Min Pool Size={0}",
                    minPoolSize);

            Stopwatch sw = new Stopwatch();

            sw.Start();
            using (SqlConnection conn =
                new SqlConnection(connectionString))
            {
                conn.Open();
            }

            sw.Stop();
            Console.WriteLine("With Pooling Min Pool Size={0}, first connection elapsed {1} ms",
                minPoolSize, sw.ElapsedMilliseconds);

            sw.Reset();

            sw.Start();

            for (int i = 0; i             {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();
                }
            }

            sw.Stop();
            Console.WriteLine("With Pooling Min Pool Size={0}, average connection elapsed {1} ms",
                minPoolSize, sw.ElapsedMilliseconds / 100);
        }


其实只要在连接字符串中加入一个 Min Pool Size=n 就可以了。

调用代码

 代码如下 复制代码

 

                Test.SqlConnectionTest.OpenWithPooling(1);
                Console.WriteLine("Waiting for 10s");
                System.Threading.Thread.Sleep(10 * 1000);
                Test.SqlConnectionTest.OpenWithPooling(1);
                Console.WriteLine("Waiting for 600s");
                System.Threading.Thread.Sleep(600 * 1000);
                Test.SqlConnectionTest.OpenWithPooling(1);
 

With Pooling Min Pool Size=1, first connection elapsed 5 ms
With Pooling Min Pool Size=1, average connection elapsed 0 ms
Waiting for 10s
With Pooling Min Pool Size=1, first connection elapsed 0 ms
With Pooling Min Pool Size=1, average connection elapsed 0 ms
Waiting for 600s
With Pooling Min Pool Size=1, first connection elapsed 0 ms
With Pooling Min Pool Size=1, average connection elapsed 0 ms


我们可以看到当 Min Pool Size = 1  时,除了首次连接用时5ms以外,即便过了10分钟,用时还是0ms,物理连接没有被关闭。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Use php-fpm connection pool to improve database access performance Use php-fpm connection pool to improve database access performance Jul 07, 2023 am 09:24 AM

Overview of using php-fpm connection pool to improve database access performance: In web development, database access is one of the most frequent and time-consuming operations. The traditional method is to create a new database connection for each database operation and then close the connection after use. This method will cause frequent establishment and closing of database connections, increasing system overhead. In order to solve this problem, you can use php-fpm connection pool technology to improve database access performance. Principle of connection pool: Connection pool is a caching technology that combines a certain number of databases

How to properly close the MySQL connection pool in a Python program? How to properly close the MySQL connection pool in a Python program? Jun 29, 2023 pm 12:35 PM

How to properly close the MySQL connection pool in a Python program? When writing programs in Python, we often need to interact with databases. The MySQL database is a widely used relational database. In Python, we can use the third-party library pymysql to connect and operate the MySQL database. When we write database-related code, a very important issue is how to correctly close the database connection, especially when using a connection pool. Connection pooling is a management

How to avoid network connection leaks in Java development? How to avoid network connection leaks in Java development? Jun 30, 2023 pm 01:33 PM

How to solve the problem of network connection leakage in Java development. With the rapid development of information technology, network connection is becoming more and more important in Java development. However, the problem of network connection leakage in Java development has gradually become prominent. Network connection leaks can lead to system performance degradation, resource waste, system crashes, etc. Therefore, solving the problem of network connection leaks has become crucial. Network connection leakage means that the network connection is not closed correctly in Java development, resulting in the failure of connection resources to be released, thus preventing the system from working properly. solution network

How to set up MySQL connection pool using PHP? How to set up MySQL connection pool using PHP? Jun 04, 2024 pm 03:28 PM

Setting up a MySQL connection pool using PHP can improve performance and scalability. The steps include: 1. Install the MySQLi extension; 2. Create a connection pool class; 3. Set the connection pool configuration; 4. Create a connection pool instance; 5. Obtain and release connections. With connection pooling, applications can avoid creating a new database connection for each request, thereby improving performance.

MySQL connection pool usage and optimization techniques in ASP.NET programs MySQL connection pool usage and optimization techniques in ASP.NET programs Jun 30, 2023 pm 11:54 PM

How to correctly use and optimize the MySQL connection pool in ASP.NET programs? Introduction: MySQL is a widely used database management system that features high performance, reliability, and ease of use. In ASP.NET development, using MySQL database for data storage is a common requirement. In order to improve the efficiency and performance of database connections, we need to correctly use and optimize the MySQL connection pool. This article will introduce how to correctly use and optimize the MySQL connection pool in ASP.NET programs.

Use MySQL connection pool in Node.js program to optimize performance Use MySQL connection pool in Node.js program to optimize performance Jun 30, 2023 pm 10:07 PM

How to properly use MySQL connection pool in Node.js program to optimize performance? With the continuous development of Internet applications, databases have become the core of most applications. In Node.js, MySQL is one of the most commonly used relational databases. However, in high concurrency situations, using MySQL connections directly will cause performance degradation. To solve this problem, we can use MySQL connection pool to optimize performance. A connection pool is a collection of established connection objects. Through the connection pool, the application

Transaction performance usage and management skills of MySQL connection pool in Node.js Transaction performance usage and management skills of MySQL connection pool in Node.js Jun 30, 2023 pm 06:24 PM

How to correctly use and manage transaction performance of MySQL connection pool in Node.js program? Introduction: With the continuous development of Internet technology, Node.js has become a very popular server-side development language. In many Web applications, the transaction performance of the database plays a crucial role in the stability and high reliability of the system. MySQL is an open source relational database management system that is widely used in Node.js programs. This article will focus on how to correctly

Detailed explanation of HTTP client and connection pool of Gin framework Detailed explanation of HTTP client and connection pool of Gin framework Jun 23, 2023 am 10:19 AM

The Gin framework is a lightweight web framework designed to provide a high-performance and high-availability web processing model. In the Gin framework, HTTP client and connection pool are very important components. This article will delve into the underlying implementation details of the HTTP client and connection pool in the Gin framework. 1. HTTP client The HTTP client is the core component in the Gin framework for sending HTTP requests. In the Gin framework, there are many different ways to implement HTTP clients, but the two most commonly used ways are

See all articles