本手册下载

X DevAPI用户指南/.../ 使用连接池连接到单个MySQL服务器

2.2.3使用连接池连接单个MySQL服务器

X DevAPI支持连接池,这可以减少打开许多连接到MySQL服务器的应用程序的开销。连接由Client对象作为池管理。当使用客户端打开新的会话时,在打开新的网络连接之前,会尝试从池中检索现有的、当前未使用的连接,然后重新设置和重用该连接。

连接池使用单个键值对配置(请参见使用键值对连接),它包含一个名为.的值。Key是另一组键-值对,包含下列表中描述的键的任意组合:

表2.1配置连接池选项

选项 意义 默认的
启用 启用连接池。当该选项设置为时,将返回常规的非连接池连接,并忽略下面列出的其他连接池选项。 真正的
最大尺寸 池中允许的最大连接数 25
maxIdleTime 在关闭连接之前,允许一个连接在队列中闲置的最大毫秒数。零表示无穷大。 0
queueTimeout 一个请求等待连接变为可用的最大毫秒数。零表示无穷大 0

关闭会话将底层连接标记为未使用,并将其返回到Client对象的连接池。

关闭Client对象将关闭它管理的所有连接,使Client创建的所有会话失效,并销毁托管池。

请注意

MySQL Shell不支持连接池。

node . js JavaScript代码

Var mysqlx = require('@mysql/xdevapi');Var客户端= 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() //客户端池中的连接变为空闲}).then(() => {return client. getsession ()}) .then(session => {console.log(session.inspect()) return client.close() //关闭所有连接并销毁池})

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 . scheme . getcollections ()) {Console.WriteLine(colle . name);}} // session. dispose()被调用,会话在池中变为空闲}// client.Dispose()被调用,然后所有会话被关闭,池被销毁

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()

Java代码

//获取新的ClientFactory()//从ClientFactory获取客户端cli = cf.getClient(this. getclient)baseUrl,“{\“池\”:{\“启用\”:真的,\“最大容量\”:8,\“maxIdleTime \”:30000年,\“queueTimeout \”:10000}}");Session sess = cli.getSession();//正常使用Session //关闭客户端后使用cli.close();

c++代码

使用名称空间mysqlx;客户端cli("user:password@host_name/db_name", ClientOption::POOL_MAX_SIZE, 7);Session sess = cli.getSession();//使用Session sess通常cli.close();//关闭所有session

连接器/ c++代码使用X DevAPI为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);//使用sess之前mysqlx_close_client(cli);//关闭session session