5、SpringBoot整合数据源druid及多数据源使用
2018-10-21 本文已影响167人
小manong
一、阿里巴巴druid数据源简介
1.优势
- 可以监控数据库访问性能,Druid内置提供了一个功能强大的StatFilter插件,能够详细统计SQL的执行性能,这对于线上分析数据库访问性能有帮助。
- 替换DBCP和C3P0。Druid提供了一个高效、功能强大、可扩展性好的数据库连接池。
- 数据库密码加密。直接把数据库密码写在配置文件中,这是不好的行为,容易导致安全问题。DruidDruiver和DruidDataSource都支持PasswordCallback。
- SQL执行日志,Druid提供了不同的LogFilter,能够支持Common-Logging、Log4j和JdkLog,你可以按需要选择相应的LogFilter,监控你应用的数据库访问情况。
- 扩展JDBC,如果你要对JDBC层有编程的需求,可以通过Druid提供的Filter-Chain机制,很方便编写JDBC层的扩展插件。
- 阿里巴巴支持,有较好的实践背景,值得信赖,目前很多的公司应用于生产上。
2.番外篇
- 关于druid和springboot默认数据源HikariDataSource之间性能论战。
二、springboot整合druid使用并完成sql监控
1.maven依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
2.数据源相关配置
server.port=8080
# 数据库访问配置
# 主数据源
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=123456
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
######################### Druid连接池的配置信息 #################
spring.druid.initialSize=5 #初始化连接大小
spring.druid.minIdle=5 #最小连接池数量
spring.druid.maxActive=20 #最大连接池数量
spring.druid.maxWait=60000 #获取连接时最大等待时间,单位毫秒
spring.druid.timeBetweenEvictionRunsMillis=60000 #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.druid.minEvictableIdleTimeMillis=300000 #配置一个连接在池中最小生存的时间,单位是毫秒
spring.druid.validationQuery=SELECT 1 FROM DUAL #测试连接
spring.druid.testWhileIdle=true #申请连接的时候检测,建议配置为true,不影响性能,并且保证安全性
spring.druid.testOnBorrow=false #获取连接时执行检测,建议关闭,影响性能
spring.druid.testOnReturn=false #归还连接时执行检测,建议关闭,影响性能
spring.druid.poolPreparedStatements=false #是否开启PSCache,PSCache对支持游标的数据库性能提升巨大,oracle建议开启,mysql下建议关闭
spring.druid.maxPoolPreparedStatementPerConnectionSize=20 #开启poolPreparedStatements后生效
spring.druid.filters=stat,wall,log4j #配置扩展插件,常用的插件有=>stat:监控统计 log4j:日志 wall:防御sql注入
spring.druid.connectionProperties='druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000' #通过connectProperties属性来打开mergeSql功能;慢SQL记录
注意:可以直接使用上面在配置文件中的配置,然后借助springboot自动装配机制完成配置加载。但是直接默认使用springboot自动加载的话,有时候容易出现bug,最好自己封装下,还可以灵活配置调用。
@Configuration
public class DruidConfiguration {
@Configuration
public class DruidConfiguration {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driverClassName}")
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
@Primary
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(url);
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) {
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
...
}
3.配置druid相关的sql监控
(1)StatViewServlet是一个标准的javax.servlet.http.HttpServlet,使用时候需要注入
- 根据配置中的url-pattern来访问内置监控页面,如果是上面的配置/druid/*,内置监控页面的首页是/druid/index.html
- 配置allow和deny。deny优先于allow,如果在deny列表中,就算在allow列表中,也会被拒绝。如果allow没有配置或者为空,则允许所有访问
- 配置resetEnable,在StatViewSerlvet输出的html页面中,有一个功能是Reset All,执行这个操作之后,会导致所有计数器清零,重新计数。你可以通过配置参数关闭它。
(2)statFilter用于采集web-jdbc关联监控的数据。 - exlusions配置经常需要排除一些不必要的url,比如.js,/jslib/等等。配置在init-param中。
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
servletRegistrationBean.addInitParameter("allow","127.0.0.1"); //设置ip白名单
servletRegistrationBean.addInitParameter("deny","192.168.0.19");//设置ip黑名单,优先级高于白名单
//设置控制台管理用户
servletRegistrationBean.addInitParameter("loginUsername","root");
servletRegistrationBean.addInitParameter("loginPassword","root");
//是否可以重置数据
servletRegistrationBean.addInitParameter("resetEnable","false");
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean statFilter(){
//创建过滤器
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
//设置过滤器过滤路径
filterRegistrationBean.addUrlPatterns("/*");
//忽略过滤的形式
filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
4.测试
- 开启应用,发现出错了显示,Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Priority,这是由于druid打印sql语句时候依赖于log4j,所以导入log4j依赖包:
...
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
... -
启动成功后,如下操作
druid监控登录
druid监控界面
二、springboot多数据源使用
1.数据准备阶段
-
先在数据库中创建好test1库和test2库,然后分别插入数据
创建数据库
2.application.properties中配置
//主数据源
spring.datasource.primary.url=jdbc:mysql://localhost:3306/test1
spring.datasource.primary.username=root
spring.datasource.primary.password=123456
spring.datasource.primary.driverClassName=com.mysql.jdbc.Driver
spring.datasource.second.url=jdbc:mysql://localhost:3306/test2
spring.datasource.second.username=root
spring.datasource.second.password=123456
spring.datasource.second.driverClassName=com.mysql.jdbc.Driver
3.java配置文件中配置
@Configuration
public class DruidConfiguration {
@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;
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
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) {
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
//根据不同数据库来配置
//=========================配置primary数据源================
@Bean(name = "primaryDatasource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
@Primary
public DataSource primaryDatasource() {
return dataSource();
}
@Bean(name = "primaryTransactionManager")
@Primary
public DataSourceTransactionManager primaryTransactionManager() {
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(primaryDatasource());
return transactionManager;
}
@Bean(name = "primaryJdbcTemplate")
@Primary
public JdbcTemplate primaryJdbcTemplate(
) {
DataSource dataSource = primaryDatasource();
return new JdbcTemplate(dataSource);
}
//=========================配置second数据源================
@Bean(name = "secondDatasource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondDatasource() {
return dataSource();
}
@Bean(name = "secondTransactionManager")
public DataSourceTransactionManager secondTransactionManager() {
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(secondDatasource());
return transactionManager;
}
@Bean(name = "secondJdbcTemplate")
public JdbcTemplate secondJdbcTemplate(
) {
DataSource dataSource = secondDatasource();
return new JdbcTemplate(dataSource);
}
...}
4.测试controller
@RestController
public class MultiDataSourceController {
@Qualifier("primaryJdbcTemplate")
@Autowired
private JdbcTemplate primaryJdbcTemplate;
@Qualifier("secondJdbcTemplate")
@Autowired
private JdbcTemplate secondJdbcTemplate;
//测试primary
@RequestMapping("/primary")
public String primaryDatasourceTest(){
String sql="select * from user";
List<User> primaryUserList = primaryJdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
return JSON.toJSONString(primaryUserList);
}
//测试second
@RequestMapping("/second")
public String secondDatasourceTest(){
String sql="select * from user";
List<User> secondUserList = secondJdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
return JSON.toJSONString(secondUserList);
}
}
5.测试
- 启动浏览器,先访问http://localhost:8080/primary
访问test1数据库 - 然后访问http://localhost:8080/second
访问test2数据库