要在Spring Boot中整合Druid數(shù)據(jù)源,可以按照以下步驟進(jìn)行操作:
1. 添加Druid和數(shù)據(jù)庫驅(qū)動的依賴:在`pom.xml`(Maven項目)或`build.gradle`(Gradle項目)中添加Druid和數(shù)據(jù)庫驅(qū)動的依賴,例如MySQL驅(qū)動:
<!-- Druid 數(shù)據(jù)源依賴 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
<!-- MySQL 驅(qū)動依賴 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2. 配置Druid數(shù)據(jù)源:在`application.properties`或`application.yml`中添加Druid數(shù)據(jù)源的配置,包括URL、用戶名、密碼等信息。例如:
# 數(shù)據(jù)源配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# Druid 連接池配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
3. 啟用Druid監(jiān)控頁面:在Spring Boot的啟動類上添加`@ServletComponentScan`注解,用于掃描Druid監(jiān)控頁面的Servlet:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
@ServletComponentScan // 啟用Servlet組件掃描
public class SpringBootApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootApp.class, args);
}
}
4. 配置Druid監(jiān)控頁面的訪問路徑和登錄賬號密碼:在`application.properties`或`application.yml`中添加以下配置:
# 配置Druid監(jiān)控頁面訪問路徑
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
# 配置Druid監(jiān)控頁面登錄賬號密碼
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin
5. 啟動應(yīng)用程序:啟動你的Spring Boot應(yīng)用程序,Druid數(shù)據(jù)源將會自動初始化并可通過訪問配置的監(jiān)控頁面路徑進(jìn)行查看。
通過以上步驟,你就成功地將Druid數(shù)據(jù)源整合到Spring Boot項目中了。你可以通過Druid監(jiān)控頁面查看數(shù)據(jù)庫連接池的狀態(tài)、SQL監(jiān)控、性能統(tǒng)計等信息。