Spring boot项目整合阿里巴巴druid数据库连接池,Java开发自学技巧
为了在Spring Boot项目中整合阿里巴巴的Druid数据库连接池,你需要按照以下步骤操作:
- 在
pom.xml
中添加Druid依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>
- 在
application.properties
或application.yml
中配置Druid数据库连接池:
# 数据库连接信息
spring.datasource.url=jdbc:mysql://localhost:3306/your_database
spring.datasource.username=your_username
spring.datasource.password=your_password
# 使用Druid数据库连接池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 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.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.time-between-eviction-runs-millis=60000
- 确保你的Spring Boot应用中已经启用了Druid监控服务(可选):
@Configuration
@ConditionalOnClass(DruidDataSource.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class DruidConfig {
@Bean
public ServletRegistrationBean<StatViewServlet> druidServlet() {
ServletRegistrationBean<StatViewServlet> servletRegistrationBean =
new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
// 可选配置
servletRegistrationBean.addInitParameter("loginUsername", "your_username");
servletRegistrationBean.addInitParameter("loginPassword", "your_password");
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean<WebStatFilter> druidFilter() {
FilterRegistrationBean<WebStatFilter> filterRegistrationBean =
new FilterRegistrationBean<>(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
}
完成以上步骤后,Druid数据库连接池将会被自动配置并整合到你的Spring Boot项目中。你可以通过访问http://<your_host>:<port>/<context-path>/druid
来访问Druid提供的监控页面,查看数据库连接池的状态和监控信息。
评论已关闭