Druid数据库连接池就是这么简单
前言
本章节主要讲解Druid数据库连接池,为什么要学Druid数据库连接池呢??
我的知识储备数据库连接池有两种->C3P0,DBCP,可是现在看起来并不够用阿~当时学习C3P0的时候,觉得这个数据库连接池是挺强大的。看过的一些书上也是多数介绍了这两种数据库连接池,自己做的Demo也是使用C3P0。可是现在看起来这两种都不够了~业界发展得真快呀
上面的我就没有打码了,都是一些热心的开发者评论,正因为他们的评论才促使我会去学更好的东西,也希望大家多多指点~
于是乎,我就花一点时间去学习Druid数据库连接池了…如果有错的地方往指正~~
Druid数据库连接池是阿里的,因此文档是有中文版本的,英语不好学起来也不用那么头疼.
一、Druid介绍
Druid一般的用处有两个:
所以本文主要是使用Druid作为数据库连接池并且使用一下实时监控应用,做个入门学习~
二、搭建Druid环境
由于简化配置,我就直接实用SpringBoot和SpringData JPA的方式来搭建一个Druid的Demo了~~~
2.1引入pom
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.5</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> <scope>test</scope> </dependency></dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.5</version> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> <scope>test</scope> </dependency></dependencies>
2.2Druid默认的配置
配置数据源的信息(Druid),和JPA相关配置~
# 数据库访问配置# 主数据源,默认的spring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/druidspring.datasource.username=rootspring.datasource.password=root# 下面为连接池的补充设置,应用到上面所有数据源中# 初始化大小,最小,最大spring.datasource.initialSize=5spring.datasource.minIdle=5spring.datasource.maxActive=20# 配置获取连接等待超时的时间spring.datasource.maxWait=60000# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒spring.datasource.timeBetweenEvictionRunsMillis=60000# 配置一个连接在池中最小生存的时间,单位是毫秒spring.datasource.minEvictableIdleTimeMillis=300000spring.datasource.validationQuery=SELECT 1 FROM DUALspring.datasource.testWhileIdle=truespring.datasource.testOnBorrow=falsespring.datasource.testOnReturn=false# 打开PSCache,并且指定每个连接上PSCache的大小spring.datasource.poolPreparedStatements=truespring.datasource.maxPoolPreparedStatementPerConnectionSize=20# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙spring.datasource.filters=stat,wall,log4j# 通过connectProperties属性来打开mergeSql功能;慢SQL记录spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000# 合并多个DruidDataSource的监控数据#spring.datasource.useGlobalDataSourceStat=true#JPA配置spring.jpa.hibernate.ddl-auto=updatespring.jpa.show-sql=truespring.jackson.serialization.indent_output=truespring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/druidspring.datasource.username=rootspring.datasource.password=root
# 下面为连接池的补充设置,应用到上面所有数据源中# 初始化大小,最小,最大spring.datasource.initialSize=5spring.datasource.minIdle=5spring.datasource.maxActive=20# 配置获取连接等待超时的时间spring.datasource.maxWait=60000# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒spring.datasource.timeBetweenEvictionRunsMillis=60000# 配置一个连接在池中最小生存的时间,单位是毫秒spring.datasource.minEvictableIdleTimeMillis=300000spring.datasource.validationQuery=SELECT 1 FROM DUALspring.datasource.testWhileIdle=truespring.datasource.testOnBorrow=falsespring.datasource.testOnReturn=false# 打开PSCache,并且指定每个连接上PSCache的大小spring.datasource.poolPreparedStatements=truespring.datasource.maxPoolPreparedStatementPerConnectionSize=20# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙spring.datasource.filters=stat,wall,log4j# 通过connectProperties属性来打开mergeSql功能;慢SQL记录spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000# 合并多个DruidDataSource的监控数据#spring.datasource.useGlobalDataSourceStat=true
#JPA配置spring.jpa.hibernate.ddl-auto=updatespring.jpa.show-sql=truespring.jackson.serialization.indent_output=true
更多的配置要去看官方文档了~不过这里一般就够用了。
2.3配置监控页面
Druid的监控统计功能是通过filter-chain扩展实现,如果你要打开监控统计功能,配置StatFilter
配置druid数据源状态监控,配置一个拦截器和一个Servlet即可~
package com.example.demo;/** * Created by ozc on 2018/3/26. * * @author ozc * @version 1.0 */import com.alibaba.druid.support.http.StatViewServlet;import com.alibaba.druid.support.http.WebStatFilter;import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * druid 配置. * <p> * 这样的方式不需要添加注解:@ServletComponentScan * * @author Administrator */@Configurationpublic class DruidConfiguration { /** * 注册一个StatViewServlet * * @return */ @Bean public ServletRegistrationBean DruidStatViewServle2() { //org.springframework.boot.context.embedded.ServletRegistrationBean提供类的进行注册. ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); //添加初始化参数:initParams //白名单: servletRegistrationBean.addInitParameter("allow", "127.0.0.1"); //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page. servletRegistrationBean.addInitParameter("deny", "192.168.1.73"); //登录查看信息的账号密码. servletRegistrationBean.addInitParameter("loginUsername", "admin2"); servletRegistrationBean.addInitParameter("loginPassword", "123456"); //是否能够重置数据. servletRegistrationBean.addInitParameter("resetEnable", "false"); return servletRegistrationBean; } /** * 注册一个:filterRegistrationBean * * @return */ @Bean public FilterRegistrationBean druidStatFilter2() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter()); //添加过滤规则. filterRegistrationBean.addUrlPatterns("/*"); //添加不需要忽略的格式信息. filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return filterRegistrationBean; }}
/** * Created by ozc on 2018/3/26. * * @author ozc * @version 1.0 */
import com.alibaba.druid.support.http.StatViewServlet;import com.alibaba.druid.support.http.WebStatFilter;import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;
/** * druid 配置. * <p> * 这样的方式不需要添加注解:@ServletComponentScan * * @author Administrator */@Configurationpublic class DruidConfiguration{
/** * 注册一个StatViewServlet * * @return */ @Bean public ServletRegistrationBean DruidStatViewServle2(){ //org.springframework.boot.context.embedded.ServletRegistrationBean提供类的进行注册. ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
//添加初始化参数:initParams
//白名单: servletRegistrationBean.addInitParameter("allow", "127.0.0.1"); //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page. servletRegistrationBean.addInitParameter("deny", "192.168.1.73"); //登录查看信息的账号密码. servletRegistrationBean.addInitParameter("loginUsername", "admin2"); servletRegistrationBean.addInitParameter("loginPassword", "123456"); //是否能够重置数据. servletRegistrationBean.addInitParameter("resetEnable", "false"); return servletRegistrationBean; }
/** * 注册一个:filterRegistrationBean * * @return */ @Bean public FilterRegistrationBean druidStatFilter2(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
//添加过滤规则. filterRegistrationBean.addUrlPatterns("/*");
//添加不需要忽略的格式信息. filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return filterRegistrationBean; }
}
2.4JPA测试
POJO:
@Entitypublic class User implements Serializable { /** * serialVersionUID. */ private static final long serialVersionUID = 1L; /** * 主键. */ @Id @GeneratedValue private String id; /** * 用户名. */ private String userName = ""; /** * 手机号码. */ private String mobileNo = ""; /** * 邮箱. */ private String email = ""; /** * 密码. */ private String password = ""; /** * 用户类型. */ private Integer userType = 0; /** * 注册时间. */ private Date registerTime = new Date(); /** * 所在区域. */ private String region = ""; /** * 是否有效 0 有效 1 无效. */ private Integer validity = 0; /** * 头像. */ private String headPortrait = "";}public class User implements Serializable{
/** * serialVersionUID. */ private static final long serialVersionUID = 1L;
/** * 主键. */ @Id @GeneratedValue private String id;
/** * 用户名. */ private String userName = "";
/** * 手机号码. */ private String mobileNo = "";
/** * 邮箱. */ private String email = "";
/** * 密码. */ private String password = "";
/** * 用户类型. */ private Integer userType = 0;
/** * 注册时间. */ private Date registerTime = new Date();
/** * 所在区域. */ private String region = "";
/** * 是否有效 0 有效 1 无效. */ private Integer validity = 0;
/** * 头像. */ private String headPortrait = "";}
Controller:
@RestControllerpublic class UserController { @Autowired private UserRepos userRepos; @RequestMapping(value="saveUser") public User saveUser(){ return userRepos.save(new User()); } @RequestMapping(value="/findByUserName") public List<User> findByUserName(String userName){ return userRepos.findByUserName(userName); } @RequestMapping(value="findByUserNameLike") public List<User> findByUserNameLkie(String userName){ return userRepos.findByUserNameLike(userName); } @RequestMapping(value="findByPage") public Page<User> findByPage(Integer userType){ return userRepos.findByUserType(userType, new PageRequest(1, 5)); }}public class UserController{
@Autowired private UserRepos userRepos;
@RequestMapping(value="saveUser") public User saveUser(){ return userRepos.save(new User()); }
@RequestMapping(value="/findByUserName") public List<User> findByUserName(String userName){ return userRepos.findByUserName(userName); }
@RequestMapping(value="findByUserNameLike") public List<User> findByUserNameLkie(String userName){ return userRepos.findByUserNameLike(userName); }
@RequestMapping(value="findByPage") public Page<User> findByPage(Integer userType){ return userRepos.findByUserType(userType, new PageRequest(1, 5)); }
}
Repository:
public interface UserRepos extends JpaRepository<User, String> { /** * 通过用户名相等查询 * * @param userName 用户名 * @return */ List<User> findByUserName(String userName); /** * 通过名字like查询 * * @param userName 用户名 * @return */ List<User> findByUserNameLike(String userName); /** * 通过用户名和手机号码查询 * * @param userName 用户名 * @param mobileNo 手机号码 * @return */ User findByUserNameAndMobileNo(String userName, String mobileNo); /** * 根据用户类型,分页查询 * * @param userType 用户类型 * @param pageable * @return */ Page<User> findByUserType(Integer userType, Pageable pageable); /** * 根据用户名,排序查询 * * @param userName 用户名 * @param sort * @return */ List<User> findByUserName(String userName, Sort sort);}interface UserRepos extends JpaRepository<User, String>{
/** * 通过用户名相等查询 * * @param userName 用户名 * @return */ List<User> findByUserName(String userName);
/** * 通过名字like查询 * * @param userName 用户名 * @return */ List<User> findByUserNameLike(String userName);
/** * 通过用户名和手机号码查询 * * @param userName 用户名 * @param mobileNo 手机号码 * @return */ User findByUserNameAndMobileNo(String userName, String mobileNo);
/** * 根据用户类型,分页查询 * * @param userType 用户类型 * @param pageable * @return */ Page<User> findByUserType(Integer userType, Pageable pageable);
/** * 根据用户名,排序查询 * * @param userName 用户名 * @param sort * @return */ List<User> findByUserName(String userName, Sort sort);
}
在页面上访问:http://localhost:8080/findByUserName?userName=Java3y
结果:
三、最后
本文只是简单的对Druid进行入门,Druid是一个非常好的开源数据库连接池框架,更多的资料可看GitHub的文档。
参考资料:
如果文章有错的地方欢迎指正,大家互相交流。习惯在微信看技术文章,想要获取更多的Java资源的同学,可以关注微信公众号:Java3y
Druid数据库连接池就是这么简单相关推荐
- Druid数据库连接池就这么简单
前言 本章节主要讲解Druid数据库连接池,为什么要学Druid数据库连接池呢?? 我的知识储备数据库连接池有两种->C3P0,DBCP,可是现在看起来并不够用阿~当时学习C3P0的时候,觉得这 ...
- Druid数据库连接池监控的使用
Druid数据库连接池 1. Druid是什么? Druid是Java语言中最好的数据库连接池,由阿里巴巴团队开发.Druid能够提供强大的监控和扩展功能. github地址为http ...
- Druid数据库连接池超时问题com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 1000, active 10
问题描述: com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 1000, active 10at com.alibab ...
- Druid数据库连接池使用参考
一:添加相应依赖 druid-1.0.9.jar: mysql-connector-java-5.1.48-bin.jar 二:编写properties文件 放置位置在src中: driverClas ...
- log4j mysql 异步_spring boot:配置druid数据库连接池(开启sql防火墙/使用log4j2做异步日志/spring boot 2.3.2)...
一,druid数据库连接池的功能? 1,Druid是阿里巴巴开发的号称为监控而生的数据库连接池 它的优点包括: 可以监控数据库访问性能 SQL执行日志 SQL防火墙 2,druid的官方站: http ...
- spring boot、mybatis集成druid数据库连接池,实现mysql cluster HA负载均衡访问
spring boot.mybatis集成druid数据库连接池,实现mysql cluster HA负载均衡访问 1.原理实现介绍 本质来说使用连接池是为了节省创建.关闭数据库连接的资源消耗,从而提 ...
- 使用Druid数据库连接池整合MyBatis Plus时,出现Error attempting to get column 'startTime' from result set. 类似错误
问题描述: 使用Druid数据库连接池整合MyBatis Plus3.2.0时,出现Error attempting to get column 'startTime' from result set ...
- springboot 使用Druid数据库连接池
Druid 阿里开源的数据库连接池 选择的理由: Druid 经历了阿里双十一的场景,足以可见其性能. Druid 有完整的监控,可以实时监控数据库状态及sql的执行时间. 提供有丰富的监控器,自定义 ...
- java银行管理系统(MySql+JDBC+数据库(Druid数据库连接池)+GUI)重要代码有解析注释
java银行管理系统 小白又来水博客了 文章目录 java银行管理系统 一.项目需求与分析: 二.知识及有关技术的概述: 三.银行管理系统需求的具体实现: 四.部分功能预览: 五.Last: 一.项目 ...
最新文章
- C语言学习之输入两个正整数m和n,求其最大公约数和最小公倍数。
- C++ WinForm Application Designer issue
- 优化if-else代码的八种方案
- 出租车计费java_java 计程车计费
- html5抽奖转盘生成器
- Java根据关键字在PDF/Word插入图片
- 论文 | 科研软件 —— SPSS Statistics V26.0安装及注册教程
- 2021年9月电子学会图形化四级编程题解析含答案:成语接龙
- ICP(Iterative Closest Point)算法和Umeyama算法
- 基于51单片机霍尔汽车自行车码表测速测里程显示proteus仿真原理图PCB
- APP全栈工程师修炼之路(二)
- .NET 中的程序集
- [转]jackson json字符串、map、java对象的转换例子
- 盗号、薅羊毛、机器注册、恶意爬虫——618大促背后涌动的欺诈暗流
- 烤仔观察 | 哈耶克最后的预言
- 计算机原理-浮点数存储
- MIT公开课: Python 笔记6 二分法,牛顿-拉夫森方法,列表
- python中多分支结构可以不用else吗_Python3基础 多分支结构 if-elif-else
- 交换芯片相关(Broadcom)
- 提交输入框的值使用js把值与百度ULR进行拼接然后搜索