Spring BootでのTomcat接続プールの設定

Spring BootでのTomcat接続プールの構成

1. 概要

Spring Bootは、プレーンなSpringプラットフォームの上に配置された、意見がありながら強力な抽象化レイヤーであり、スタンドアロンおよびWebアプリケーションの開発を簡単にします。 Spring Bootは、最小限のフットプリントでJavaアプリケーションを実行およびテストすることを目的とした、いくつかの便利な「スターター」依存関係を提供します。

One key component of these starter dependencies is spring-boot-starter-data-jpa。 これにより、JPAを使用し、HikariCPTomcat JDBC Connection Poolなどの一般的なJDBC接続プールの実装を使用して本番データベースを操作できます。

このチュートリアルでは、we’ll learn how to configure a Tomcat connection pool in Spring Boot

2. Mavenの依存関係

Spring Bootは、その優れたパフォーマンスとエンタープライズ対応機能により、HikariCPをデフォルトの接続プールとして使用します。

SpringBootが接続プールデータソースを自動的に構成する方法は次のとおりです。

  1. Spring BootはクラスパスでHikariCPを探し、存在する場合はデフォルトでそれを使用します

  2. クラスパスにHikariCPが見つからない場合、SpringBootはTomcatJDBC接続プールが利用可能であればそれを取得します。

  3. これらのオプションのどちらも使用できない場合、Spring BootはApache Commons DBCP2を選択します(使用可能な場合)。

デフォルトのHikariCPの代わりにTomcatJDBC接続プールを構成するには、exclude HikariCP from the spring-boot-starter-data-jpa dependency and add the tomcat-jdbc Maven dependencypom.xmlに変更します。


    org.springframework.boot
    spring-boot-starter-data-jpa
    
        
            com.zaxxer
            HikariCP
        
    


    org.apache.tomcat
    tomcat-jdbc
    9.0.10


    com.h2database
    h2
    1.4.197
    runtime

この単純なアプローチにより、@Configurationクラスを記述したり、プログラムでDataSource Beanを定義したりすることなく、Tomcat接続プールを使用してSpringBootを取得できます。

It’s also worth noting that in this case, we’re using the H2 in-memory databaseSpring Boot will autoconfigure H2 for us, without having to specify a database URL, user, and password

対応する依存関係を“pom.xml”ファイルに含める必要があり、SpringBootが残りの作業を行います。

または、“spring.datasource.type”プロパティを使用して“application.properties” file,内のit’s possible to skip the connection pool scanning algorithm that Spring Boot uses and explicitly specify a connection pooling datasource

spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
// other spring datasource properties

3. 「application.properties」ファイルを使用した接続プールの調整

Spring BootでTomcat接続プールを正常に構成したら、it’s very likely that we’ll want to set up some additional properties, for optimizing its performance and suiting some specific requirements

“application.properties”ファイルでこれを行うことができます。

spring.datasource.tomcat.initial-size=15
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=15
spring.datasource.tomcat.min-idle=8
spring.datasource.tomcat.default-auto-commit=true

プールの初期サイズ、アイドル状態の接続の最大数と最小数など、いくつかの追加の接続プールプロパティを構成していることに注意してください。

また、いくつかのHibernate固有のプロパティを指定することもできます。

# Hibernate specific properties
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.id.new_generator_mappings=false

4. 接続プールのテスト

SpringBootが接続プールを正しく構成したことを確認するための簡単な統合テストを書いてみましょう。

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootTomcatConnectionPoolIntegrationTest {

    @Autowired
    private DataSource dataSource;

    @Test
    public void givenTomcatConnectionPoolInstance_whenCheckedPoolClassName_thenCorrect() {
        assertThat(dataSource.getClass().getName())
          .isEqualTo("org.apache.tomcat.jdbc.pool.DataSource");
    }
}

5. サンプルコマンドラインアプリケーション

すべての接続プール配管がすでに設定されているので、簡単なコマンドラインアプリケーションを作成しましょう。

そうすることで、Spring Data JPA(および推移的にSpring Boot)が提供する強力なDAOレイヤーを使用して、H2データベースでいくつかのCRUD操作を実行する方法を確認できます。

Spring Data JPAの使用を開始する方法の詳細なガイドについては、this articleを確認してください。

5.1. Customerエンティティクラス

まず、ナイーブなCustomerエンティティクラスを定義しましょう。

@Entity
@Table(name = "customers")
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Column(name = "first_name")
    private String firstName;

    // standard constructors / getters / setters / toString
}

5.2. CustomerRepositoryインターフェース

この場合、いくつかのCustomerエンティティ.でCRUD操作を実行するだけです。さらに、指定された姓に一致するすべての顧客をフェッチする必要があります。

したがって、all that we have to do is to extend Spring Data JPA’s CrudRepository interface and define a tailored method

public interface CustomerRepository extends CrudRepository {
    List findByLastName(String lastName);
}

これで、Customerエンティティをその姓で簡単にフェッチできます。

5.3. CommandLineRunnerの実装

最後に、少なくともデータベース内のいくつかのCustomerエンティティとverify that our Tomcat connection pool is actually workingを永続化する必要があります。

Spring BootのCommandLineRunnerインターフェースの実装を作成しましょう。 Spring Bootは、アプリケーションを起動する前に実装をブートストラップします。

public class CommandLineCrudRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(CommandLineCrudRunner.class);

    @Autowired
    private final CustomerRepository repository;

    public void run(String... args) throws Exception {
        repository.save(new Customer("John", "Doe"));
        repository.save(new Customer("Jennifer", "Wilson"));

        logger.info("Customers found with findAll():");
        repository.findAll().forEach(c -> logger.info(c.toString()));

        logger.info("Customer found with findById(1L):");
        Customer customer = repository.findById(1L)
          .orElseGet(() -> new Customer("Non-existing customer", ""));
        logger.info(customer.toString());

        logger.info("Customer found with findByLastName('Wilson'):");
        repository.findByLastName("Wilson").forEach(c -> {
            logger.info(c.toString());
        });
    }
}

簡単に言うと、CommandLineCrudRunnerクラスは最初にいくつかのCustomerエンティティをデータベースに保存します。 次に、findById()メソッドを使用して最初のものをフェッチします。 最後に、findByLastName()メソッドを使用して顧客を取得します。

5.4. SpringBootアプリケーションの実行

もちろん、最後に行う必要があるのは、サンプルアプリケーションを実行することだけです。 次に、Spring Boot / Tomcat接続プールが動作しているのを確認できます。

@SpringBootApplication
public class SpringBootConsoleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootConsoleApplication.class);
    }
}

6. 結論

このチュートリアルでは、Spring BootでTomcat接続プールを構成および使用する方法を学びました。 さらに、Spring Boot、Tomcat接続プール、およびH2データベースを簡単に操作できることを示すために、基本的なコマンドラインアプリケーションを開発しました。

いつものように、このチュートリアルに示されているすべてのコードサンプルはover on GitHubで利用できます。