1. 概要

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

これらのスターター依存関係の重要なコンポーネントの1つは、spring-boot-starter-data-jpaです。 これにより、 JPA を使用し、HikariCPTomcatJDBC ConnectionPoolなどの一般的なJDBC接続プールの実装を使用して本番データベースを操作できます。

このチュートリアルでは、Spring BootでTomcat接続プールを構成する方法を学習します。

2. Mavenの依存関係

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

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

  1. Spring BootはクラスパスでHikariCPを検索し、存在する場合はデフォルトでそれを使用します
  2. クラスパスにHikariCPが見つからない場合、Spring BootはTomcat JDBC接続プール(使用可能な場合)を取得します。
  3. これらのオプションのいずれも使用できない場合、SpringBootはApache Commons DBCP2 を選択します(使用可能な場合)。

デフォルトのHikariCPの代わりにTomcatJDBC接続プールを構成するには、HikariCPをspring-boot-starter-data-jpa依存関係から除外し、tomcat-jdbcMaven依存関係に追加します。 ] pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <exclusions>
        <exclusion>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jdbc</artifactId>
    <version>9.0.10</version>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.197</version>
    <scope>runtime</scope>
</dependency>

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

この場合、H2インメモリデータベースを使用していることにも注意してください。 Spring Bootは、データベースのURL、ユーザー、およびパスワードを指定しなくても、H2を自動構成します

対応する依存関係を「pom.xml」ファイルに含める必要があります。残りはSpringBootが行います。

または、 Spring Bootが使用する接続プールスキャンアルゴリズムをスキップして、「application.properties」ファイル で接続プールデータソースを明示的に指定することもできます。 “ spring .datasource.type” プロパティの使用:

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

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

Spring BootでTomcat接続プールを正常に構成したら、パフォーマンスを最適化し、特定の要件に適合させるために、いくつかの追加のプロパティを設定する必要があります

これは、「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. 接続プールのテスト

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

@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の使用を開始する方法の詳細なガイドについては、この記事を確認してください。

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インターフェース

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

したがって、必要なのは、Spring Data JPAのCrudRepositoryインターフェースを拡張し、調整されたメソッドを定義することだけです。

public interface CustomerRepository extends CrudRepository<Customer, Long> {
    List<Customer> findByLastName(String lastName);
}

これで、Customerエンティティをその姓で簡単に取得できます。

5.3. CommandLineRunnerの実装

最後に、少なくともいくつかの Customer エンティティをデータベースに保持し、Tomcat接続プールが実際に機能していることを確認する必要があります

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. 結論

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

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