Druid は監視機能に特化した高性能なデータベース接続プールです。この記事では、Spring Boot アプリケーションに Druid を組み込む基本的な手順を紹介します。
1. 依存関係の追加
Spring Boot との統合には、druid-spring-boot-starter を使用します。
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
2. 設定プロパティの記述
application.properties に以下のように Druid 固有の設定を記述します。既存の Spring Boot + MyBatis の構成を前提としています。
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# Druid 接続プール設定
spring.datasource.druid.initial-size=1
spring.datasource.druid.min-idle=1
spring.datasource.druid.max-active=20
spring.datasource.druid.max-wait=60000
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.test-on-return=true
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
3. 監視機能の有効化(プロパティベース)
Druid の Web コンソールや SQL 監視機能は、Java 設定クラスを作成せずに、プロパティファイルだけで有効化できます。
# WebStatFilter 設定
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
spring.datasource.druid.web-stat-filter.session-stat-enable=true
spring.datasource.druid.web-stat-filter.session-stat-max-count=1000
# StatViewServlet 設定
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
spring.datasource.druid.stat-view-servlet.login-username=druid
spring.datasource.druid.stat-view-servlet.login-password=123456
spring.datasource.druid.stat-view-servlet.allow=127.0.0.1
spring.datasource.druid.stat-view-servlet.deny=192.168.0.19
spring.datasource.druid.stat-view-servlet.reset-enable=false
4. Spring コンポーネントの監視設定
MyBatis Mapper インターフェースなどの Spring Bean を対象に AOP ベースの監視を行う場合、以下のプロパティを追加します。
spring.datasource.druid.aop-patterns=com.example.mapper.*
5. 動作確認
アプリケーションを起動後、ブラウザで http://127.0.0.1:8080/druid/index.html にアクセスし、設定したユーザー名・パスワードでログインします。SQL 実行や URL、セッションなどのリアルタイム監視情報が表示されます。