spring中druid用法
时间: 2023-08-13 10:07:43 浏览: 96
在Spring中使用Druid连接池可以提高数据库连接的性能和可靠性。具体的使用步骤如下:
1. 在项目中引入Druid的依赖:
```xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
```
2. 在application.properties或application.yml配置文件中添加Druid相关配置信息,如下所示:
```properties
# 数据库连接池配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# Druid连接池配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.initial-size=10
spring.datasource.druid.min-idle=10
spring.datasource.druid.max-active=100
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.validation-query-timeout=3
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
spring.datasource.druid.filters=stat,wall,log4j
spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
```
其中,spring.datasource.type=com.alibaba.druid.pool.DruidDataSource表示使用Druid连接池;spring.datasource.druid开头的属性为Druid连接池的配置信息。
3. 在Spring Boot的启动类中添加Druid监控Servlet和Filter:
```java
@Bean
public ServletRegistrationBean<StatViewServlet> druidServletRegistrationBean() {
ServletRegistrationBean<StatViewServlet> servletRegistrationBean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
// IP白名单
servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
// IP黑名单(优先级高于白名单)
// servletRegistrationBean.addInitParameter("deny", "");
// 控制台管理用户
servletRegistrationBean.addInitParameter("loginUsername", "admin");
servletRegistrationBean.addInitParameter("loginPassword", "admin");
// 是否能够重置数据 禁用HTML页面上的“Reset All”功能
servletRegistrationBean.addInitParameter("resetEnable", "false");
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean<WebStatFilter> druidFilterRegistrationBean() {
FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<>(new WebStatFilter());
// 添加过滤规则
filterRegistrationBean.addUrlPatterns("/*");
// 添加不需要忽略的格式信息
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
```
4. 在需要使用数据库连接的地方,注入DruidDataSource即可:
```java
@Autowired
private DruidDataSource dataSource;
```
需要注意的是,Druid连接池的配置比较灵活,可以根据实际需求进行相应的调整。
阅读全文