springboot配置druid连接池
时间: 2023-05-30 18:06:32 浏览: 77
Spring Boot 配置 Druid 连接池的步骤如下:
1. 在 pom.xml 中添加 Druid 的依赖:
```
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
```
2. 在 application.properties 或 application.yml 中配置 Druid 的相关参数,例如:
```
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
# Druid 连接池的参数
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
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
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
```
3. 在启动类上添加 @ServletComponentScan 注解:
```
@ServletComponentScan
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
4. 在启动类中添加 Druid 的 Servlet 配置:
```
@Bean
public ServletRegistrationBean druidServlet() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String, String> initParams = new HashMap<>();
initParams.put("loginUsername", "admin");
initParams.put("loginPassword", "admin");
servletRegistrationBean.setInitParameters(initParams);
return servletRegistrationBean;
}
```
以上是在 Spring Boot 中配置 Druid 连接池的简单步骤
阅读全文