アプリケーションがPythonプログラミング言語を使用しており、アプリケーションとApsaraDB RDS for MySQLインスタンスとの間に短期間の接続などの接続が頻繁に確立されている場合、またはRDSインスタンスへの接続が最大数に達している場合は、DBUtilsを使用してRDSインスタンスに接続できます。 DBUtilsは、Pythonプログラミング言語の接続プールです。 DBUtilsは、アプリケーションがRDSインスタンスに接続する頻度を減らし、RDSインスタンスのメインスレッドのオーバーヘッドを減らすのに役立ちます。 このトピックでは、DBUtilsを使用してRDSインスタンスに接続する方法について説明します。
前提条件
バージョンが3.7から3.12の範囲のPythonがアプリケーションサーバーにインストールされます。
サーバーのIPアドレスがRDSインスタンスのIPアドレスホワイトリストに追加されます。 詳細については、「IPアドレスホワイトリストの設定」をご参照ください。
説明アプリケーションがRDSインスタンスと同じリージョンおよび仮想プライベートクラウド (VPC) にあるElastic Compute Service (ECS) インスタンスにデプロイされている場合、IPアドレスホワイトリストを設定する必要はありません。
準備
DBUtilsのインストール: 次のコマンドを実行して、サーバーにDBUtilsをインストールします。 この例では、DBUtils 3.1.0が使用されます。 詳細については、「DBUtils」をご参照ください。
pip install DBUtils==3.1.0
PyMySQLのインストール: 次のコマンドを実行してPyMySQLをインストールします。 サーバーをRDSインスタンスに接続する場合は、PyMySQLが必要です。
pip install pymysql
DBUtilsを使用したRDSインスタンスへの接続
関連モジュールのインポート: DBUtilsを使用してRDSインスタンスに接続する前に、次のコマンドを実行して関連モジュールをインポートします。
from dbutils.pooled_db import PooledDB import importlib import pymysql
DBUtilsDemo
クラスのビルド: 後続の操作でメソッドの呼び出しと管理を容易にするために、DBUtilsDemo
クラスを作成し、__init__
メソッドで接続プールパラメーターを設定し、_connect
メソッドと_close
メソッドをクラスに追加して接続プールからの接続を取得および返すことを推奨します。class DBUtilsDemo: def __init__(self, url, user, password, database): db_config = { "host": url, "port": 3306, "user": user, "db": database, "password": password, "charset": "utf8", "connect_timeout": 3, "read_timeout": 10, "write_timeout": 10 } ''' For more information about common parameters of the DBUtils connection pool, see the "Common parameters of the connection pool" section of this topic. mincached: the initial number of idle connections in the connection pool. The value 0 specifies that no connections are established upon startup. maxcached: the maximum number of idle connections in the pool. The value 0 or None specifies that no limits are imposed. maxshared: the maximum number of shared connections. The value 0 or None specifies that all connections are dedicated. maxconnections: the maximum number of connections that are allowed in most cases. The value 0 or None specifies that no limits are imposed. blocking: the operation that is performed when the number of connections exceeds the upper limit. maxusage: the maximum number of times that a connection can be reused. The value 0 or None specifies that no limits are imposed. ''' self.pooled = PooledDB(pymysql, maxcached=20, maxshared=0, maxconnections=100, maxusage=20, **db_config) # Obtain a connection from the connection pool. def _connect(self): try: r = self.pooled.connection() return r except Exception as e: print("Failed to connect:" + str(e)) # Return a connection to the connection pool. def _close(self, conn, stmt): if stmt: stmt.close() if conn: conn.close()
初期化
DBUtilsDemo
クラスの__main__
関数RDSインスタンスに接続します。
の後DBUtilsDemo
クラスが構築されている場合、__main_関数でクラスを初期化し、RDSインスタンス上のデータベースへの接続を取得できます。if __name__ == '__main__': # The endpoint of the RDS instance. You must specify the internal or public endpoint of the RDS instance based on the requirements of your server. url = 'rm-bp**************.mysql.rds.aliyuncs.com' # Specify the username that is used to access the RDS instance. user = 'dbuser' # Specify the password that is used to access the RDS instance. password = '****' # Specify the name of the database to which you want to connect. database = 'dbtest' # Obtain the connection object. poolUtils = DBUtilsDemo(url, user, password, database)
接続プールの共通パラメータ
DBUtilsを使用してRDSインスタンスに接続する場合、RDSインスタンスがより安定して効率的に実行されるように、接続プールに必要なパラメーターを設定することを推奨します。 __init__
メソッドによって呼び出されるPooledDB
関数でパラメーターを設定できます。
潜在的なリスクと不確実性を最小限に抑え、システムの安定性と信頼性を確保するために、本番環境で新しいパラメーター値を適用する前に、完全な機能とパフォーマンステストを実行することをお勧めします。
推奨される設定
DBUtils接続プールを使用する場合は、データベースの実行時のリスクを軽減するためにパラメーターを設定することを推奨します。 下表に、各パラメーターを説明します。
パラメーター | 説明 | デフォルト値 | 推奨値 | 補足 |
maxcached | アイドル接続の最大数。 | 0 | 20 |
|
maxusage | 接続を再利用できる最大回数。 | なし | 10から20 |
|
connect_timeout | データベースに接続するためのタイムアウト時間。 単位: 秒。 | 10 | 3 |
|
read_timeout | データベースからデータを読み取るためのタイムアウト時間。 単位: 秒。 | なし | 10から60 |
|
write_timeout | データベースにデータを書き込むためのタイムアウト時間。 単位: 秒。 | なし | 10から60 |
|
オプション設定
DBUtilsを使用してRDSインスタンスに接続する場合、パラメーターを設定してデータベースのパフォーマンスを向上させることができます。 下表に、各パラメーターを説明します。
パラメーター | 説明 | デフォルト値 | 推奨値 | 補足 |
maxconnections | 接続プールで許可される接続の最大数。 | 0 | 100 |
|
デフォルト設定
パラメーターのデフォルト設定を使用するか、ビジネス要件に基づいてパラメーターを変更できます。 下表に、各パラメーターを説明します。
パラメーター | 説明 | デフォルト値 | 推奨値 | 補足 |
ミンチ | 接続プール内のアイドル接続の初期数。 | 0 | / |
|
maxshared | 共有接続の最大数。 | 0 | / |
|
ブロッキング | 最大接続数を超えた場合に使用される処理方法。 | False | / |
|
setsession | 接続が確立されたときに実行されるSQL文。 | なし | / | このパラメーターを使用して、セッションレベルのパラメーターを設定したり、その他の初期化操作を実行したりできます。 |
リセット | 接続が接続プールに返されるときに、接続のステータスをリセットする必要があるかどうかを指定します。 | 正しい | / |
|
failures | データベース接続が失敗したときの再接続の数。 | なし | / | / |
ping | アイドル接続に対して実行されるハートビート検出操作。 | 1 | / | このパラメーターを使用して、接続の可用性を確認できます。 |
その後のデータベース操作
データベースで操作を実行する場合は、DBUtilsDemo
クラスにカスタムメソッドを追加できます。
読み取りリクエスト
1. カスタムメソッドを追加します。
データベースの読み取り要求を処理するには、DBUtilsDemo
クラスにカスタムメソッドを追加する必要があります。 次のサンプルコードは、1行および複数行のデータをクエリする方法の例を示しています。
単一行のデータを照会します。
def select_row(self, sql): connection = self._connect() statement = None try: statement = connection.cursor() statement.execute(sql) row = statement.fetchone() return row except Exception as e: print(e) finally: self._close(connection, statement)
複数行のデータを照会します。
def select_rows(self, sql): connection = self._connect() statement = None try: statement = connection.cursor() statement.execute(sql) rows = statement.fetchall() return rows except Exception as e: print(e) finally: self._close(connection, statement)
2. カスタムメソッドを呼び出します。
データを照会するには、__main__
関数で次のメソッドを呼び出す必要があります。
if __name__ == '__main__':
# Configure the required connection parameters and connect to the database.
url = 'rm-bp**************.mysql.rds.aliyuncs.com'
user = 'dbuser'
password = '****'
database = 'dbtest'
poolUtils = DBUtilsDemo(url, user, password, database)
# Query a single row of data.
row = poolUtils.select_row("select * from tb where id = 'i001' limit 1")
print(row)
# Query multiple rows of data.
rows = poolUtils.select_rows("select * from tb")
print(rows)
書き込みリクエスト
1. カスタムメソッドを追加します。
DBUtilsDemo
クラスにカスタムメソッドを追加して、INSERT
、UPDATE
、DELETE
、CREATE TABLE
リクエストなどのデータベースに対する書き込みリクエストを処理する必要があります。 次のサンプルコードは、バインドパラメーターを持つ書き込み要求と、バインドパラメーターを持たない書き込み要求の例を示しています。
バインドされたパラメーターを持つ書き込み要求
def upsert_data_prams(self, sql_upsert, params): connection = self._connect() statement = None try: statement = connection.cursor() statement.execute(sql_upsert, params) connection.commit() except Exception as e: print(e) finally: self._close(connection, statement)
バインドされたパラメーターなしの書き込み要求
def upsert_data(self, sql_upsert): connection = self._connect() statement = None try: statement = connection.cursor() statement.execute(sql_upsert) connection.commit() except Exception as e: print(e) finally: self._close(connection, statement)
2. カスタムメソッドを呼び出します。
SQL文を実行するには、__main__
関数で次のメソッドを呼び出す必要があります。
if __name__ == '__main__':
# Configure the required parameters and connect to the database.
url = 'rm-bp**************.mysql.rds.aliyuncs.com'
user = 'dbuser'
password = '****'
database = 'dbtest'
poolUtils = DBUtilsDemo(url, user, password, database)
# Process the write request without bound parameters.
poolUtils.upsert_data("insert into tb(id,name,address) values ('i001','n001','a001')")
# Process the write request with bound parameters.
params = ['i002', 'n002', 'a002']
poolUtils.upsert_data_prams("insert into tb(id,name,address) values (%s,%s,%s)", params)
関連ドキュメント
Jave接続プールの詳細については、「Druidを使用したApsaraDB RDS For MySQLインスタンスへの接続」をご参照ください。
Goドライバーパッケージの詳細については、「Go-MySQL-driverを使用したApsaraDB RDS For MySQLインスタンスへの接続」をご参照ください。
ApsaraDB RDS For MySQLのデータベースプロキシの接続プール機能の詳細については、「接続プール機能の設定」をご参照ください。