LoginSignup
37
36

More than 5 years have passed since last update.

Spring Boot でプーリング設定をする

Last updated at Posted at 2016-02-24

Spring Bootでデータベースのコネクションプーリングするのにハマって
「はじめてのSpring Boot」の槙さんにTwitterで助けて頂いたのでお礼代わりに書き残しておきます。

プーリングの設定はapplication.ymlに書きます。

application.yml
spring:
  datasource:
    url=jdbc:oracle:thin:@localhost:1521/orcl
    driverClassName=oracle.jdbc.driver.OracleDriver
    username: scott
    password:tiger
    maxActive: 15
    maxIdle: 10
    minIdle: 5
    initialSize: 0

とここまではすぐわかったんですが、Configクラスでdatasourceを生成する際に@ConfigurationPropertiesで設定を拡張しないと有効になりません!

Config.java
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource dataSource() {
    DataSourceBuilder factory = DataSourceBuilder
            .create(this.properties.getClassLoader())
            .driverClassName(this.properties.getDriverClassName())
            .url(this.properties.getUrl())
            .username(this.properties.getUsername())
            .password(this.properties.getPassword());
    return factory.build();
}

これだけだと「ConfigurationProperties勝手に使うんじゃねえ!」って警告が出るのでpom.xmlにも設定を追加してやります。

pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

こちらで詳しく説明してくださっていました。
stackoverflow - Spring-Boot: How do I set JDBC pool properties like maximum number of connections?
が、DataSourceAutoConfiguration.CONFIGURATION_PREFIXの書き方は今はサポートされていないのかエラーになりました。

ConfigurationPropertiesの書き方はこちらも参考にさせて頂きました。
rororo1989のブログ - Spring Bootその6 db周りね!
prefixってそういうことなのね。

2016/10/29追記 SpringBoot1.4の場合

application.ymlに書くだけでちゃんと動きました。

application.yml
spring:
  datasource:
    driverClassName: oracle.jdbc.driver.OracleDriver
    url: jdbc:oracle:thin:@localhost:1521/orcl
    username: scott
    password: tiger
    sqlScriptEncoding: UTF-8
#pooling setting
spring.datasource.tomcat:
    maxActive: 15
    maxIdle: 10
    minIdle: 5
    initialSize: 2

Tomcatじゃない人は別途確認してください。
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-1.4-Release-Notes#datasource-binding

37
36
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
37
36