アプリケーションがJavaプログラミング言語を使用しており、アプリケーションとApsaraDB RDS for MySQLインスタンスの間で短期間の接続などの接続が頻繁に確立されている場合、またはRDSインスタンスへの接続が最大数に達している場合は、Druidを使用してRDSインスタンスに接続できます。 Druidは、Javaプログラミング言語の接続プールです。 Druidは、アプリケーションがRDSインスタンスに接続する頻度を減らし、RDSインスタンスのメインスレッドのオーバーヘッドを減らすのに役立ちます。 このトピックでは、Druidを使用してRDSインスタンスに接続する方法について説明します。
前提条件
Java Development Kit (JDK) 1.8以降がアプリケーションサーバーにインストールされます。
サーバーのIPアドレスがRDSインスタンスのIPアドレスホワイトリストに追加されます。 詳細については、「IPアドレスホワイトリストの設定」をご参照ください。
説明アプリケーションがRDSインスタンスと同じリージョンおよび仮想プライベートクラウド (VPC) にあるElastic Compute Service (ECS) インスタンスにデプロイされている場合、IPアドレスホワイトリストを設定する必要はありません。
準備
次のセクションでは、Druidを使用してRDSインスタンスに接続する前の準備について、Mavenプロジェクトを例として説明します。
Apache Mavenは、開発者に標準化されたJavaプロジェクト構築プロセスと依存関係管理メカニズムを提供するJavaプロジェクト管理ツールです。 詳細については、「Apache Mavenへようこそ」をご参照ください。 MavenベースのJavaプロジェクトには、標準化されたディレクトリ構造があります。 pom.xmlファイルはプロジェクト記述ファイルで、src/main/javaディレクトリにはプロジェクトのJavaソースコードが格納され、src/main/resourcesディレクトリにはプロジェクトのリソースファイルが格納されます。
Druidのインストール:
pom.xmlファイルのdependenciesセクションに次の依存関係を追加します。 Druid 1.2.13以降を使用することを推奨します。<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.19</version> </dependency>プロジェクトで
druid-spring-boot-starterを使用する場合は、pom.xmlファイルのdependenciesセクションからDruid-spring-boot-starterが依存するdruid依存関係を除外し、明示的にDruid依存関係を追加する必要があります。 サンプルコード:<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.19</version> <exclusions> <exclusion> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.19</version> </dependency>
Druidを使用したRDSインスタンスへの接続
接続プールのパラメーターの設定: プロジェクトの
src/main/resourcesディレクトリにdruid.propertiesという名前のファイルを作成し、次の内容をファイルに追加してDruid接続プールのパラメーターを設定します。 パラメーターの詳細については、「接続プールの共通パラメーター」をご参照ください。説明RDSインスタンスのエンドポイントとポート番号を取得する方法の詳細については、「インスタンスエンドポイントとポートの表示と管理」をご参照ください。
# The name of the driver class. You do not need to modify this parameter. driverClassName=com.mysql.jdbc.Driver # Specify the url, username, and password parameters based on your business requirements. url=jdbc:mysql://rm-bp**************.mysql.rds.aliyuncs.com:3306/database username=**** password=**** # Specify the number of connections that are established during initialization. initialSize=20 # Specify the minimum number of idle connections. minIdle=20 # Specify the maximum number of active connections in a connection pool. maxActive=100 # Specify the maximum period of time that a physical connection can be reused. phyTimeoutMillis=3600000 # Specify the maximum waiting time to obtain a connection. Unit: milliseconds. If no available connections exists in the connection pool and the maximum number of connections is reached, the request from the application to obtain a connection is blocked until the maximum waiting time elapses. We recommend that you retain the parameter setting. maxWait=5000 # Specify the timeout period for establishing a TCP connection between the database driver and the server on which the RDS instance resides. Unit: milliseconds. connectTimeout=20000 # Specify the socket timeout period for an application that is waiting for a response after the application sends data, such as SQL statements, over a TCP connection. Unit: milliseconds. socketTimeout=60000 # Configure the required parameters to verify connections. We recommend that you retain the parameter settings. testWhileIdle=true testOnBorrow=false testOnReturn=false # Configure the parameters related to caching. The PreparedStatement parameter is set to true, which indicates that caching is enabled. We recommend that you retain the parameter settings. poolPreparedStatements=true maxPoolPreparedStatementPerConnectionSize=100Druid接続プールを使用してRDSインスタンスに接続する: 必要な依存関係を
src/main/javaディレクトリのソースコードファイルにインポートし、DruidPoolDemoクラスを構築し、Druid接続プールからJava Database Connectivity (JDBC) 接続に関する情報を取得し、RDSインスタンスにアクセスします。// Import the required dependencies. package com.aliyun.rdsfinops.collector.impl; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class DruidPoolDemo { private static DataSource dataSource = null; String tableName = "sql_table_test"; // Load parameter settings. static { Properties properties = new Properties(); // Obtain the configurations of the connection pool. InputStream inputStream = DruidPoolDemo.class.getClassLoader().getResourceAsStream("druid.properties"); try { properties.load(inputStream); // Initialize the connection pool. dataSource = DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { e.printStackTrace(); } } /* View subsequent database operations in the following sections: Create a table: public void createTable() Insert data: public void insertData() Query data: public void selectData() Delete data: public void deleteData() */ }
接続プールの共通パラメータ
Druidを使用してRDSインスタンスに接続する場合、RDSインスタンスが安定して効率的に実行されるように、接続プールに次のパラメーターを設定することを推奨します。
潜在的なリスクと不確実性を最小限に抑え、システムの安定性と信頼性を確保するために、本番環境で新しいパラメーター値を適用する前に、完全な機能とパフォーマンステストを実行することをお勧めします。
推奨される設定
Druid接続プールを使用する場合は、データベースの実行時のリスクを軽減するためにパラメーターを設定することを推奨します。 下表に、各パラメーターを説明します。
パラメーター | 説明 | デフォルト値 | 推奨値 | 補足 |
initialSize | 接続プールの初期化中に確立された接続の数。 | 0 | 20から80 |
|
minIdle | アイドル接続の最小数。 | 0 | 20から80 |
|
maxActive | 接続プール内のアクティブな接続の最大数。 | 8 | 100 |
|
phyTimeoutMillis | 物理接続を再利用できる最大期間。 単位: ミリ秒。 | -1 | 28800000に3600000 |
|
maxWait | 接続を取得するための最大待機時間。 単位: ミリ秒。 | -1 | 5000 |
|
connectTimeout | 接続タイムアウト期間。 単位: ミリ秒。 | 10000 | 3000 |
|
socketTimeout | ソケットのタイムアウト期間。 単位: ミリ秒。 | 10000 | 60000に10000 |
|
testWhileIdle | アイドル接続検出を有効にするかどうかを指定します。 | false | true | このパラメーターを |
オプション設定
他のパラメーターを設定して、データベースのパフォーマンスを向上できます。 下表に、各パラメーターを説明します。
パラメーター | 説明 | デフォルト値 | 推奨値 | 補足 |
poolPreparedStatements | PreparedStatementオブジェクトをキャッシュするかどうかを指定します。 | true | true |
|
maxPoolPreparedStatementPerConnectionSize | 各接続によってキャッシュされるPreparedStatementオブジェクトの最大数。 | 10 | 100 |
|
デフォルト設定
特定のパラメーターのデフォルト設定を使用したり、ビジネス要件に基づいてパラメーターを変更したりできます。 下表に、各パラメーターを説明します。
パラメーター | 説明 | デフォルト値 | 推奨値 | 補足 |
failFast | コネクション取得時にエラーが発生した場合に実行される操作。 | false | false |
|
timeBetweenEvictionRunsMillis | アイドル接続が検出される間隔。 単位: ミリ秒。 | 60,000 | 60,000 |
|
その後のデータベース操作
データベースで操作を実行する場合は、ユーザー定義関数をDruidPoolDemoクラスに追加できます。 次のサンプルコードは、テーブルの作成、テーブルへのデータの挿入、データの照会、およびデータの削除の方法の例を示しています。
テーブルの作成
String tableName = "sql_table_test";
public void createTable() throws SQLException {
// Create a table.
try (Connection connection = dataSource.getConnection()) {
try (Statement statement = connection.createStatement()) {
String sql = "create table if not exists " + tableName + "(id VARCHAR(255), name VARCHAR(255), PRIMARY KEY (id))";
int ret = statement.executeUpdate(sql);
System.out.println(ret);
}
}
}データの挿入
String tableName = "sql_table_test";
public void insertData(){
// Insert data to the table.
try (Connection connection = dataSource.getConnection()) {
String sql = "insert into " + tableName + "(id,name) values(?,?)";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, "aa");
ps.setString(2, "bb");
int ret = ps.executeUpdate();
System.out.println(ret);
}
} catch (SQLException e) {
e.printStackTrace();
}
}クエリデータ
String tableName = "sql_table_test";
public void selectData() throws SQLException {
// Query data in the table.
try (Connection connection = dataSource.getConnection()) {
String sql = "select * from " + tableName + " where id=?";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, "aa");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String id = rs.getString(1);
String name = rs.getString(2);
System.out.println("id=" + id);
System.out.println("name=" + name);
}
}
}
}データの削除
String tableName = "sql_table_test";
public void deleteData(){
// Delete data from the table.
try (Connection connection = dataSource.getConnection()) {
String sql = "delete from " + tableName + " where id=?";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setString(1, "aa");
ps.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}関連ドキュメント
Python接続プールの詳細については、「DBUtilsを使用したApsaraDB RDS For MySQLインスタンスへの接続」をご参照ください。
Goドライバーパッケージの詳細については、「Go-MySQL-driverを使用したApsaraDB RDS For MySQLインスタンスへの接続」をご参照ください。
ApsaraDB RDS For MySQLのデータベースプロキシの接続プール機能の詳細については、「接続プール機能の設定」をご参照ください。