项目已托管于 GitHub:y0ngb1n/spring-boot-samples,欢迎 Star, Fork 😘
添加依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>${alibaba-druid.version}</version> </dependency>
|
配置属性
spring: datasource: url: jdbc:h2:mem:recommend username: sa password: type: com.alibaba.druid.pool.DruidDataSource druid: initial-size: 5 min-idle: 10 max-active: 20 keep-alive: true min-evictable-idle-time-millis: 600000 max-evictable-idle-time-millis: 900000 time-between-eviction-runs-millis: 2000 max-wait: 800 connect-properties: socketTimeout=3000;connectTimeout=1200 validation-query: select 1 test-while-idle: true test-on-borrow: false test-on-return: false phy-max-use-count: 1000
|
多数据源
添加配置
spring: datasource: type: com.alibaba.druid.pool.DruidDataSource druid: use-global-data-source-stat: true foo: url: jdbc:h2:mem:foo username: foo password: initial-size: 5 min-idle: 10 max-active: 20 maxWait: 800 bar: url: jdbc:h2:mem:bar username: bar password: initial-size: 5 min-idle: 10 max-active: 20 maxWait: 1200
|
创建数据源
@Configuration public class DruidConfig {
@Bean @Primary @ConfigurationProperties("spring.datasource.druid.foo") public DataSource dataSourceFoo() { return DruidDataSourceBuilder.create().build(); }
@Bean @ConfigurationProperties("spring.datasource.druid.bar") public DataSource dataSourceBar() { return DruidDataSourceBuilder.create().build(); } }
|
配置 Filter
spring: datasource: druid: filters: config,stat,slf4j filter: config: enabled: true stat: enabled: true log-slow-sql: true slow-sql-millis: 5000 slf4j: enabled: true wall: enabled: true stat-view-servlet: enabled: true login-username: yangbin login-password: yangbin
|
监控数据
@RestController public class DruidStatController {
@GetMapping("/druid/stat") public Object druidStat() { return DruidStatManagerFacade.getInstance().getDataSourceStatDataList(); } }
|
🔗️ 参考链接