学习新思想争做新青年
一、Druid介绍
1.1、Druid是一个JDBC组件,它包括三部分:
- DruidDriver 代理Driver,能够提供基于Filter-Chain模式的插件体系。
- DruidDataSource 高效可管理的数据库连接池。
- SQLParser
1.2、Druid可以做什么?
① 可以监控数据库访问性能,Druid内置提供了一个功能强大的StatFilter插件,能够详细统计SQL的执行性能,这对于线上分析数据库访问性能有帮助。
② 替换DBCP和C3P0。Druid提供了一个高效、功能强大、可扩展性好的数据库连接池。
③ 数据库密码加密。直接把数据库密码写在配置文件中,这是不好的行为,容易导致安全问题。DruidDruiver和DruidDataSource都支持PasswordCallback。
④ SQL执行日志,Druid提供了不同的LogFilter,能够支持Common-Logging、Log4j和JdkLog,你可以按需要选择相应的LogFilter,监控你应用的数据库访问情况。
二、环境搭建
2.1、创建一个干净的SpringBoot的项目;
2.2、向pom.xml—><dependencies>...</dependencies>
中导入依赖;
<!-- JDBC -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!-- 数据库连接池:Druid德鲁伊-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.4</version>
</dependency>
<!-- 打印日记 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- web支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.3、配置application.yml参数
# 设置服务端口为8000
server:
port: 8000
# 对JDBC的一些配置
spring:
datasource:
username: root
password: 123456
# url: jdbc:mysql://localhost:3306/数据库名?useSSL=false&serverTimezone=UTC
url: jdbc:mysql://localhost:3306/druidtest?useSSL=false&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#druid数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许报错,java.lang.ClassNotFoundException: org.apache.Log4j.Properity
#则导入log4j 依赖就行
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
2.4、测试一下数据源是否配置成功;
package com.baidou;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@SpringBootTest
class DemoApplicationTests {
@Autowired //依赖注入
DataSource dataSource;
@Test
void contextLoads() {
}
@Test
void testDruid() throws SQLException {
// 查看默认数据源 class com.zaxxer.hikari.HikariDataSource
System.out.println(dataSource.getClass()); //class com.alibaba.druid.pool.DruidDataSource
//获取数据库连接
Connection connection = null;
try {
connection = dataSource.getConnection();
System.out.println(connection); // //获取数据库连接
} catch (SQLException e) {
e.printStackTrace();
} finally {
//释放资源
connection.close();
}
}
}
2.5、配置 DruidConfig ;
package com.baidou.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
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;
import javax.sql.DataSource;
import java.util.HashMap;
/**
* Created by baidou on 2021/2/26.
*
* class:DruidConfig
*/
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
}
//后台监控
@Bean
public ServletRegistrationBean statViewServlet() {
//注册 ServletBean
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
//设置后台登录的账号密码
HashMap<String, String> initParameters = new HashMap<>();
initParameters.put("loginUsername", "admin");
initParameters.put("loginPassword", "123456");
//允許谁能访问 initParameters.put("username","password");
bean.setInitParameters(initParameters);//初始化参数
return bean;
}
//Filter
public FilterRegistrationBean webStatFilter() {
//注册 FilterBean
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
//可以过滤那些请求?
HashMap<String, String> initParameters = new HashMap<>();
//这些东西不进行统计
initParameters.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParameters);//初始化参数
return bean;
}
}
2.6、启动项目(雷布斯说不服我们跑个分嘻嘻);
然后访问我们之前配置的URL:
http://localhost:8000/druid/login.html
http://localhost:8000/druid/
输入我们之前配置的用户名和密码;
username:admin
password:123456
我这个数据库没创建表所以就非常干净哈哈哈!
大功告成!!!