springboot整合druid数据库连接池并开启监控
简介
Druid是一个关系型数据库连接池,它是阿里巴巴的一个开源项目。Druid支持所有JDBC兼容的数据库,包括Oracle、MySQL、Derby、PostgreSQL、SQL Server、H2等。Druid在监控、可扩展性、稳定性和性能方面具有明显的优势。通过Druid提供的监控功能,可以实时观察数据库连接池和SQL查询的工作情况。使用Druid连接池,在一定程度上可以提高数据库的访问性能。
本博文采用的gradle方式构建的springboot项目,因此导入jar包也是以gradle方式。
一:创建boot项目,导入druid依赖
dependencies {
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.mybatis.spring.boot:mybatis-spring-boot-starter:1.1.1'
compile 'mysql:mysql-connector-java:5.1.37'
compile 'com.alibaba:druid:1.0.27'
}
二:在application-dev.yaml中配置druid属性
spring:
datasource:
dialect: mysql
url: 'jdbc:mysql://127.0.0.1:3306/test_db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false'
username: 'admin'
password: 'admin'
driver-class-name: 'com.mysql.jdbc.Driver'
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 1
minIdle : 5
maxActive: 10
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
filters: stat,wall,slf4j
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
useGlobalDataSourceStat: true
monitorUserName: admin
monitorPassword: admin
resetEnable: false
allow:
deny:
exclusions:
session:
store-type: none #springboot默认session存储在redis中,由于本项目暂时未配置redis;故设置store-type:none
三:自定义数据库连接池(可跳过)
package com.chenpt.config; import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.StringUtils; import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.Arrays; /**
* Created by admin on 2017/1/18.
*/
@Configuration
@EnableTransactionManagement
@MapperScan(value = "com.chenpt")
public class DatabaseConfiguration implements EnvironmentAware { /**
* 日志记录器
*/
private static final Logger logger = LoggerFactory.getLogger(DatabaseConfiguration.class); @Resource
private Environment env; private RelaxedPropertyResolver resolver; @Override
public void setEnvironment(Environment environment) {
this.env = environment;
this.resolver = new RelaxedPropertyResolver(environment,"spring.datasource.");
} //注册dataSource
@Bean(initMethod = "init", destroyMethod = "close")
public DruidDataSource dataSource() throws SQLException {
if (StringUtils.isEmpty(resolver.getProperty("url"))) {
logger.error("Your database connection pool configuration is incorrect!"
+ " Please check your Spring profile, current profiles are:"
+ Arrays.toString(env.getActiveProfiles()));
throw new ApplicationContextException(
"Database connection pool is not configured correctly");
}
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(resolver.getProperty("driver-class-name"));
druidDataSource.setUrl(resolver.getProperty("url"));
druidDataSource.setUsername(resolver.getProperty("username"));
druidDataSource.setPassword(resolver.getProperty("password"));
druidDataSource.setInitialSize(Integer.parseInt(resolver.getProperty("initialSize")));
druidDataSource.setMinIdle(Integer.parseInt(resolver.getProperty("minIdle")));
druidDataSource.setMaxActive(Integer.parseInt(resolver.getProperty("maxActive")));
druidDataSource.setMaxWait(Integer.parseInt(resolver.getProperty("maxWait")));
druidDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(resolver.getProperty("timeBetweenEvictionRunsMillis")));
druidDataSource.setMinEvictableIdleTimeMillis(Long.parseLong(resolver.getProperty("minEvictableIdleTimeMillis")));
druidDataSource.setValidationQuery(resolver.getProperty("validationQuery"));
druidDataSource.setTestWhileIdle(Boolean.parseBoolean(resolver.getProperty("testWhileIdle")));
druidDataSource.setTestOnBorrow(Boolean.parseBoolean(resolver.getProperty("testOnBorrow")));
druidDataSource.setTestOnReturn(Boolean.parseBoolean(resolver.getProperty("testOnReturn")));
druidDataSource.setPoolPreparedStatements(Boolean.parseBoolean(resolver.getProperty("poolPreparedStatements")));
druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(resolver.getProperty("maxPoolPreparedStatementPerConnectionSize")));
druidDataSource.setFilters(resolver.getProperty("filters"));
return druidDataSource;
} @Bean public PlatformTransactionManager transactionManager() throws SQLException {
return new DataSourceTransactionManager(dataSource());
}
}
四:配置druid(关键性配置)
package com.chenpt.config; import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment; import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map; /**
* @Author: ch
* @Description:
* @Date: created in 2018/7/26
* @Modified By:
*/
@Configuration
public class DruidConfigration implements EnvironmentAware {
@Resource
Environment environment; /**
* 日志记录器
*/
private static final Logger logger = LoggerFactory.getLogger(DruidConfigration.class); private RelaxedPropertyResolver resolver; @Override
public void setEnvironment(Environment environment) {
this.environment = environment;
this.resolver = new RelaxedPropertyResolver(environment,"spring.datasource.");
} @Bean
public ServletRegistrationBean druidServlet() {
logger.info("init Druid Servlet Configuration ");
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
servletRegistrationBean.setServlet(new StatViewServlet());
servletRegistrationBean.addUrlMappings("/druid/*");
Map<String, String> initParameters = new HashMap<>();
initParameters.put("loginUsername", resolver.getProperty("monitorUserName"));// 用户名
initParameters.put("loginPassword",resolver.getProperty("monitorPassword"));// 密码
// 禁用HTML页面上的“Reset All”功能
initParameters.put("resetEnable", resolver.getProperty("resetEnable"));
// IP白名单 (没有配置或者为空,则允许所有访问)
initParameters.put("allow", resolver.getProperty("allow"));
//IP黑名单 (存在共同时,deny优先于allow)
initParameters.put("deny", resolver.getProperty("deny"));
servletRegistrationBean.setInitParameters(initParameters);
return servletRegistrationBean;
} @Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
}
到此数据库配置就完成了,接下来启动程序,可以登录druid监控中心(http://localhost:8767/druid/login.html)
详情页
springboot整合druid数据库连接池并开启监控的更多相关文章
- springboot项目整合druid数据库连接池
Druid连接池是阿里巴巴开源的数据库连接池项目,后来贡献给Apache开源: Druid的作用是负责分配.管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个: D ...
- SpringBoot集成druid数据库连接池的简单使用
简介 Druid是阿里巴巴旗下Java语言中最好的数据库连接池.Druid能够提供强大的监控和扩展功能. 官网: https://github.com/alibaba/druid/wiki/常见问题 ...
- springboot整合druid连接池、mybatis实现多数据源动态切换
demo环境: JDK 1.8 ,Spring boot 1.5.14 一 整合durid 1.添加druid连接池maven依赖 <dependency> <groupId> ...
- SpringBoot 配置Druid数据库连接池
创建数据库连接池配置类 package com.boot.config; import com.alibaba.druid.pool.DruidDataSource; import com.aliba ...
- springboot+mybatis+druid数据库连接池
参考博客https://blog.csdn.net/liuxiao723846/article/details/80456025 1.先在pom.xml中引入druid依赖包 <!-- 连接池 ...
- Springboot整合Hikari数据库连接池,密码加密
1.application.yml配置 spring: datasource: jdbcUrl: jdbc:mysql://127.0.0.1:3306/jby?serverTimezone=UTC& ...
- springBoot(13)---整合Druid实现多数据源和可视化监控
SpringBoot整合Druid实现多数据源和可视化监控 先献上github代码地址:https://github.com/yudiandemingzi/springboot-manydatasou ...
- Springboot整合druid
目录 Springboot整合druid application.yml DruidConfig 数据监控地址:http://localhost:8080/druid Springboot整合drui ...
- SpringBoot整合Druid数据连接池
SpringBoot整合Druid数据连接池 Druid是什么? Druid是Alibaba开源的的数据库连接池.Druid能够提供强大的监控和扩展功能. 在哪里下载druid maven中央仓库: ...
随机推荐
- [转载]Oracle左连接、右连接、全外连接以及(+)号用法
Oracle 外连接(OUTER JOIN) 左外连接(左边的表不加限制) 右外连接(右边的表不加限制) 全外连接(左右两表都不加限制) 对应SQL:LEFT/RIGHT/FULL OUTER JO ...
- flask框架----设置配置文件的几种方式
设置配置文件的几种方式 ==========方式一:============ app.config['SESSION_COOKIE_NAME'] = 'session_lvning' #这种方式要把所 ...
- 处理jquery的ajax请求session过期跳转到登录页面
首先需要在拦截器中判断是否是ajax请求,如果是 if(isAjaxRequest(request)){//ajax请求 response.setHeader("sessionstatus& ...
- 使用sqlalchemy用orm方式写pipeline将scrapy item快速存入 MySQL
传统的使用scrapy爬下来的数据存入mysql,用的是在pipeline里用pymysql存入数据库, 这种方法需要写sql语句,如果item字段数量非常多的 情况下,编写起来会造成很大的麻烦. 我 ...
- 过滤特殊字符(包括过滤emoji表情)
/** * 过滤特殊字符 * @param $text * @return mixed */ public static function filterSpecialChars($text) { // ...
- Pycharm创建Django项目并访问Django
Pycharm创建Django项目并访问Django 一.Django插件 如果没有Django插件,需要先安装Django插件. 1,首先点击Default Settings,打开设置页面: 2,打 ...
- kafka学习指南(总结版)
版本介绍 从使用上来看,以0.9为分界线,0.9开始不再区分高级/低级消费者API. 从兼容性上来看,以0.8.x为分界线,0.8.x不兼容以前的版本. 总体拓扑架构 从上可知: 1.生产者不需要访问 ...
- jackson JsonPropertyOrder和@JsonIgnoreProperties注解
有些时候,我们在和外部系统交互的时候使用了json作为标准的数据交换格式,同时为了安全性考虑,增加了对报文的校验,因此我们需要确保序列化的时候参数有序且不多不少刚好,因为对外的API不像后台和前端交互 ...
- Kali系列之ettercap欺骗
ettercap在局域网中使用欺骗, 捕获对象浏览器中的图片. 环境 攻击方:kali linux, ip:192.168.137.129 目标方ip:192.168.137.130 路由器:192. ...
- [c/c++] programming之路(7)、数据类型转换、偷钱小程序、进制转换
一.数据类型转换 #include<stdio.h> //某些场合,必须进行数据类型转换,以匹配调用 void main0(){ printf();//printf不管你是什么类型,解析失 ...