目录
Druid是Java语言中最好的数据库连接池。Druid能够提供强大的监控和扩展功能。
Druid 是一个 JDBC 组件库,包含数据库连接池、SQL Parser 等组件, 被大量业务和技术产品使用或集成,经历过最严苛线上业务场景考验,是你值得信赖的技术产品。
一、JDBC连接数据库
1. 创建项目,导入需要的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2. 配置数据源
server:
port: 8085
spring:
application:
name: user-service
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/hm49?serverTimezone=UTC&useUnicode=true@characterEncoding=utf-8
username: root
password: root
3. 测试连接
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 DataApplicationTests {
@Autowired
DataSource dataSource;
/**
* 验证数据库连接
* @throws Exception
*/
@Test
void testConnection() throws Exception {
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
/**
* 验证连接池的配置信息,是否生效
* @throws Exception
*/
/*@Test
void contextLoads() throws Exception {
System.out.println(dataSource.getClass());
DruidDataSource druidDataSource = (DruidDataSource) dataSource;
System.out.println("initSize:" + druidDataSource.getInitialSize());
System.out.println("maxSize:" + druidDataSource.getMaxActive());
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}*/
}
4. 项目启动成功,能够看出连接信息
默认配置的数据源为class com.zaxxer.hikari.HikariDataSource
二、配置数据库连接池Druid
1. 添加druid的maven配置
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
2. 添加数据源的配置
server:
port: 8085
spring:
application:
name: user-service
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/hm49?serverTimezone=UTC&useUnicode=true@characterEncoding=utf-8
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
3. 重新执行测试代码,发现数据库连接池已经更改
此时配置的数据源为com.alibaba.druid.pool.DruidDataSource
4. 添加Druid其他增强的配置
官网介绍如下:常见问题 · alibaba/druid Wiki · GitHub
server:
port: 8085
spring:
application:
name: user-service
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/hm49?serverTimezone=UTC&useUnicode=true@characterEncoding=utf-8
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#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.Priority
#则导入 log4j 依赖即可,Maven 地址: https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
#第一步连接数据库
#第二步配置连接池+type
#第三部测试查询jdbcTemplate.queryForList(sql);
#第四部添加连接池配置
5. 写配置类加载Druid的配置
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.servlet.Servlet;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
@Bean
public ServletRegistrationBean druidServletRegistrationBean(){
ServletRegistrationBean<Servlet> servletRegistrationBean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
//后台允许谁可以访问
//initParams.put("allow", "localhost"):表示只有本机可以访问
//initParams.put("allow", ""):为空或者为null时,表示允许所有访问
initParams.put("allow","");
//deny:Druid 后台拒绝谁访问
// initParams.put("msb", "192.168.1.20");//表示禁止此ip访问
servletRegistrationBean.setInitParameters(initParams);
return servletRegistrationBean;
}
//配置 Druid 监控 之 web 监控的 filter
//WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
//exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
Map<String, String> initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
//"/*" 表示过滤所有请求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
6. 引入log4j的依赖
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
7. 测试一下数据库连接
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class JDBCController {
@Autowired
JdbcTemplate jdbcTemplate;
@RequestMapping("selectAll")
public List<Map<String,Object>> selectAll(){
String sql = "select * from tb_user";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}
}
8. 查看控制台的监控信息
http://localhost:8085/druid/login.html