在 Spring Boot 中集成 Druid 数据源可以通过以下步骤实现: 源代码地址:study-springboot-chapter04
-
添加依赖: 在
pom.xml文件中添加 Druid 的依赖:<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> <!-- 请根据需要选择合适的版本 --> </dependency> -
配置数据源: 在
application.yml或application.properties文件中配置 Druid 数据源的相关属性。例如,在application.yml中可以这样配置:#服务配置 server: port: 8080 spring: datasource: druid: url: jdbc:mysql://localhost:3306/platform?useUnicode=true&characterEncoding=utf- 8&useSSL=false&serverTimezone=UTC username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver initial-size: 5 max-active: 20 min-idle: 5 max-wait: 60000 validation-query: SELECT 1 test-on-borrow: true test-while-idle: true time-between-eviction-runs-millis: 60000 -
启用 Druid 的监控功能(可选) : 如果需要启用 Druid 的监控功能,可以在
application.yml中添加以下配置:spring: datasource: druid: stat-view-servlet: enabled: true url-pattern: /druid/* allow: 127.0.0.1 reset-enable: false web-stat-filter: enabled: true url-pattern: /* exclusions: *.js,*.gif,*.jpg,*.png,*.css,/druid/* -
创建 Druid 监控的 Servlet: 在 Spring Boot 的主类上加上
@ServletComponentScan注解,以启用 Druid 的监控 servlet:import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import javax.servlet.annotation.ServletComponentScan; @SpringBootApplication @ServletComponentScan public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } -
启动项目: 完成以上步骤后,启动 Spring Boot 项目,访问
http://localhost:8080/druid即可查看 Druid 的监控页面。