PDF (美式信紙) - 1.4Mb
PDF (A4) - 1.4Mb
X DevAPI 支援連線池,這可以減少應用程式開啟多個連線至 MySQL 伺服器的負擔。連線由 Client 物件以集區形式管理。當使用 Client 開啟新的工作階段時,在開啟新的網路連線之前,會嘗試從集區中擷取現有且目前未使用的連線,然後重設並重複使用該連線。
連線池是使用單一鍵值組進行設定(請參閱使用鍵值組連線),其中包含名為 pooling
的單一鍵。 pooling
鍵的值是另一組鍵值組,其中包含下表所述鍵的任意組合。
表 2.1 設定連線池的選項
選項 | 意義 | 預設值 |
---|---|---|
enabled | 啟用連線池。當選項設定為 false 時,會傳回一般非集區連線,並且忽略下面列出的其他連線池選項。 |
true |
maxSize | 集區中允許的最大連線數 | 25 |
maxIdleTime | 連線在佇列中閒置的最長時間 (毫秒),然後關閉。值為零表示無限。 | 0 |
queueTimeout | 請求等待連線可用的最長時間 (毫秒)。值為零表示無限。 | 0 |
關閉工作階段會將基礎連線標示為未使用,並將其傳回 Client 物件的連線池。
關閉 Client 物件會關閉其管理的所有連線、使 Client 建立的所有工作階段失效,並銷毀受管理的集區。
注意
MySQL Shell 不支援連線池。
Node.js JavaScript 程式碼
var mysqlx = require('@mysql/xdevapi');
var client = mysqlx.getClient(
{ user: 'user', host: 'localhost', port: 33060 },
{ pooling: { enabled: true, maxIdleTime: 30000, maxSize: 25, queueTimeout: 10000 } }
);
client.getSession()
.then(session => {
console.log(session.inspect())
return session.close() // the connection becomes idle in the client pool
})
.then(() => {
return client.getSession()
})
.then(session => {
console.log(session.inspect())
return client.close() // closes all connections and destroys the pool
})
C# 程式碼
using (Client client = MySQLX.GetClient("server=localhost;user=user:port=33060;",
new { pooling = new { Enabled = true, MaxSize = 100, MaxIdleTime=30000, QueueTimeout = 10000 } }))
{
using (Session session = client.GetSession())
{
foreach (Collection coll in session.Schema.GetCollections())
{
Console.WriteLine(coll.Name);
}
} // session.Dispose() is called and the session becomes idle in the pool
} // client.Dispose() is called then all sessions are closed and pool is destroyed
Python 程式碼
connection_string = {
'host': 'localhost',
'port': 37210,
'user': 'user',
'password': 'password'
}
client_options = {
'pooling': {
"max_size": 10,
"max_idle_time": 30000
}
}
client = mysqlx.get_client(connection_string, client_options)
session1 = client.get_session()
session2 = client.get_session()
# closing all the sessions
client.close()
Java 程式碼
//Obtain new ClientFactory
ClientFactory cf = new ClientFactory();
//Obtain Client from ClientFactory
Client cli = cf.getClient(this.baseUrl, "{\"pooling\":{\"enabled\":true, \"maxSize\":8,
\"maxIdleTime\":30000, \"queueTimeout\":10000} }");
Session sess = cli.getSession();
//Use Session as usual
//Close Client after use
cli.close();
C++ 程式碼
using namespace mysqlx;
Client cli("user:password@host_name/db_name", ClientOption::POOL_MAX_SIZE, 7);
Session sess = cli.getSession();
// use Session sess as usual
cli.close(); // close all Sessions
使用 X DevAPI for C 的 Connector/C++ 程式碼
char error_buf[255];
int error_code;
mysqlx_client_t *cli
= mysqlx_get_client_from_url(
"user:password@host_name/db_name", "{ \"maxSize\": 7 }", error_buf, &error_code
);
mysqlx_session_t *sess = mysqlx_get_session_from_client(cli);
// use sess as before
mysqlx_close_client(cli); // close session sess