Java – JDBC Driver for SQL Server on Ubuntuの自動リトライ接続 No53

自己投資としてチャレンジしている内容を Blog で公開しています。

今回は自動で接続をリトライしてくれる便利な機能を紹介します。 Microsoft JDBC Driver for SQL Server の接続文字列 (Connection String) にリトライおよび、リトライ間隔の値を追加します。(In English: Java -AutoRetry connection by JDBC Driver for SQLServer No53)

▼1. Microsoft JDBC Driver for SQL Server の接続文字列で設定可能な接続のリトライ および、リトライの間隔について (Version 9.4 以上)

Version 9.4 から、クラウドサービスには欠かせない、接続のリトライおよび、接続のリトライの間隔 が、接続文字列で指定できるようになりました。 (対象バージョンは Microsoft JDBC Driver 9.4 for SQL Server 以降なので注意ください)。

具体的には、下記パラメータを接続文字列に追記します。各種タイムアウト値を指定し、接続のリトライ “connectRetryCount” および、リトライの間隔 “connectRetryInterval” でリトライ処理を行うことで、よくあるネットワークの一時的な問題を回避します。

  • connectRetryCount (既定 1、単位 回) : リトライの回数を指定。0 から 255 まで指定可能
  • connectRetryInterval (既定 10、単位 秒) : リトライ(再試行)まで待つ時間 (秒)

▼2. SQL Server 接続失敗時の自動リトライする Java コード

2.1. 実行例

事前に作成したデータベース TeatDB を利用しています。user と password は環境にあった値に変更します。以下の例は 3 回のリトライと、次のリトライまで 15 秒待つ設定となります。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

public class ConSQLRetry2 {
    public static void main(String[] args) throws InterruptedException{
        Connection con = null;

        System.out.println("START: " + new Timestamp(new Date().getTime()));
        try {
            String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=TestDB;user=sa;password=Password;loginTimeout=30;socketTimeout=60000;queryTimeout=60;cancelQueryTimeout=60;connectRetryCount=3;connectRetryInterval=15;;encrypt=true;trustServerCertificate=true;";
            System.out.println("Connecting to SQL Server...: " + new Timestamp(new Date().getTime()));
            con = DriverManager.getConnection(connectionUrl);
        } catch (SQLException se) {
            System.out.println("Connection failed after several retries.");
            se.printStackTrace();
        }
        System.out.println("This connection ended - Current Timestamps 1: " + new Timestamp(new Date().getTime()));
    }
} 

[環境] Ubuntu 20.04.4 LTS, Microsoft SQL Server 2022 (CTP2.0) – 16.0.600.9 (x64)

2.2 接続が成功する場合

START: 2022-06-24 10:23:00.906
Connecting to SQL Server...: 2022-06-24 10:23:00.913
This connection ended - Current Timestamps 1: 2022-06-24 10:23:01.488

2.3. 接続が失敗する場合

SQL Server がリッスンしている Port 1433 の代わりに、テストのため誤った Port 1443 を指定し SQL Server に接続しました。接続失敗時、出力されたエラーは以下となります。

START: 2022-06-24 10:24:07.665
Connecting to SQL Server...: 2022-06-24 10:24:07.692
Connection failed after several retries.
This connection ended - Current Timestamps 1: 2022-06-24 10:24:37.687
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1443 has failed. Error: "Connection refused (Connection refused). Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
	at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:237)
	at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:288)
	at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2720)
	at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:761)
	at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:3180)
	at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2833)
	at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2671)
	at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1640)
	at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:936)
	at java.sql.DriverManager.getConnection(DriverManager.java:664)
	at java.sql.DriverManager.getConnection(DriverManager.java:270)
at ConSQLRetry2.main(ConSQLRetry2.java:15)

▼3. 参考情報

1 Setting the connection properties
2 Building the Connection
3 Ubuntu: Install SQL Server on Linux – SQL Server | Microsoft Docs
4 Java SQL Server on Linux に接続する方法 No.5
5 Java SQL Server on Linux に接続時の「エラーハンドリング」 & 「リトライ」方法 No6
6 Java – JDBC Driver for SQL Server の接続文字列について No7

以上です。参考になりましたら幸いです。



コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です