Druid是阿里开源的一款数据库连接池,除了常规的连接池功能外,它还提供了强大的监控和扩展功能。这对没有做数据库监控的小项目有很大的吸引力。
下列步骤可以让你无脑式的在SpringBoot2.x中使用Druid。
1.Maven中的pom文件
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.14</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
使用 Spring Boot-2.x时,如果未引入log4j,在配置 Druid 时,会遇到Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Priority的报错。因为Spring Boot默认使用的是log4j2。
2.SpringBoot 配置文件
下面是一个完整的yml文件的,其中使用mybatis作为数据库访问框架
server:
servlet:
context-path: /
session:
timeout: 60m
port: 8080
spring:
datasource:
url: jdbc:mysql://127.0.0.1:9080/hospital?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
username: root
password: root
# 环境 dev|test|pro
profiles:
active: dev
driver-class-name: com.mysql.cj.jdbc.Driver
########################## druid配置 ##########################
type: com.alibaba.druid.pool.DruidDataSource
# 初始化大小,最小,最大
initialSize: 5
minIdle: 1
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
# 校验SQL,Oracle配置 validationQuery=SELECT 1 FROM DUAL,如果不配validationQuery项,则下面三项配置无用
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
# Mybatis配置
mybatis:
mapperLocations: classpath:mapper/*.xml,classpath:mapper/extend/*.xml
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
3.配置Druid数据源实例
由于Druid暂时不在Spring Boot中的直接支持,故需要进行配置信息的定制:
SpringBoot中的配置信息无法再Druid中直接生效,需要在Spring容器中实现一个DataSource实例。
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource;
@Configuration
public class DruidDBConfig {
private Logger logger = Logger.getLogger(this.getClass()); //log4j日志
@Value("${spring.datasource.url}")
private String dbUrl;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;
@Value("${spring.datasource.initialSize}")
private int initialSize;
@Value("${spring.datasource.minIdle}")
private int minIdle;
@Value("${spring.datasource.maxActive}")
private int maxActive;
@Value("${spring.datasource.maxWait}")
private int maxWait;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.validationQuery}")
private String validationQuery;
@Value("${spring.datasource.testWhileIdle}")
private boolean testWhileIdle;
@Value("${spring.datasource.testOnBorrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.testOnReturn}")
private boolean testOnReturn;
@Value("${spring.datasource.poolPreparedStatements}")
private boolean poolPreparedStatements;
@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize;
@Value("${spring.datasource.filters}")
private String filters;
@Value("{spring.datasource.connectionProperties}")
private String connectionProperties;
@Bean // 声明其为Bean实例
@Primary // 在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
// configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
//logger.error("druid configuration initialization filter", e);
logger.error("druid configuration initialization filter", e);
e.printStackTrace();
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
}
4.过滤器和Servlet
还需要实现一个过滤器和Servlet,用于访问统计页面。
过滤器
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import com.alibaba.druid.support.http.WebStatFilter;
@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
initParams={
@WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//忽略资源
}
)
public class DruidStatFilter extends WebStatFilter {
}
Servlet
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import com.alibaba.druid.support.http.StatViewServlet;
@WebServlet(urlPatterns="/druid/*",
initParams={
@WebInitParam(name="allow",value="127.0.0.1,192.168.163.1"),// IP白名单(没有配置或者为空,则允许所有访问)
@WebInitParam(name="deny",value="192.168.1.73"),// IP黑名单 (存在共同时,deny优先于allow)
@WebInitParam(name="loginUsername",value="admin"),// 用户名
@WebInitParam(name="loginPassword",value="admin"),// 密码
@WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能
})
public class DruidStatViewServlet extends StatViewServlet {
private static final long serialVersionUID = -2688872071445249539L;
}
5.使用@ServletComponentScan注解,
使得刚才创建的Servlet,Filter能被访问,SpringBoot扫描并注册。
@SpringBootApplication()
@MapperScan("cn.china.mytestproject.dao")
//添加servlet组件扫描,使得Spring能够扫描到我们编写的servlet和filter
@ServletComponentScan
public class MytestprojectApplication {
public static void main(String[] args) {
SpringApplication.run(MytestprojectApplication.class, args);
}
}
6.Dao层
接着Dao层代码的实现,可以使用mybatis,或者JdbcTemplate等。此处不举例。
7.运行
访问http://localhost:8080/druid/login.html地址即可打开登录页面,账号在之前的Servlet代码中。
至此完成。
要了解更多,访问:https://github.com/alibaba/druid
以上就是SpringBoot 中使用 Druid 数据库连接池的实现步骤的详细内容,更多关于SpringBoot 中使用 Druid 数据库连接池的资料请关注编程网其它相关文章!