Druid数据源连接池
文章目录
1 啥是Druid
Druid是一个高效的数据查询系统,主要解决的是对于大量的基于时序的数据进行聚合查询。数据可以实时摄入,进入到Druid后立即可查,同时数据是几乎是不可变。通常是基于时序的事实事件,事实发生后进入Druid,外部系统就可以对该事实进行查询。
上面这段话是上网复制的,总的来说特点如下:
- 集成了c3p0、jdbc等数据库连接池的优点
- 自带日志监控功能
- And so on
2 SpringBoot引用Druid
先导入依赖,因为Druid自带日志监控功能,所以我们需要导入log4j依赖
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
3 配置yml文件
设置yml中属性值
spring:
datasource:
url: jdbc:mysql://192.168.18.176:3306/win_database01?useSSL=true&useUnicode=true
&characterEncoding=UTF-8&serverTimeZone=Aisa/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
type: com.alibaba.druid.pool.DruidDataSource
#SpringBoot默认是不注入这些的,需要自己绑定
#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.Properities
#则导入log4j 依赖就行
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
4 查看数据源
在SpringBoot的测试类中查看数据源
package com.xzzlx;
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 Springboot04DataApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
5 config
创建config目录,配置Druid
package com.xzzlx.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
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;
@Configuration
public class DruidConfig {
// 绑定yml中的配置
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSourece(){
return new DruidDataSource();
}
// 后台监控:web.xml ServletRegistrationBean
// 因为SpringBoot内置了servlet容器,所以没有web.xml
// 替代方法:ServletRegistrationBean注册进去
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean<StatViewServlet> bean = new
ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
// 后台需要有人登录,设置账号密码
HashMap<String, String> initParameters = new HashMap<>();
// 增加配置
// 登录key 固定的 loginUsername loginPassword
initParameters.put("loginUsername","admin");
initParameters.put("loginPassword","123456");
/* 允许谁可以访问
/* "" 表示所有人 "localhost"表示本机可以访问 还可以指定某个人
/* 想要禁止访问,""指定ip即可 例如:initParameters.put("xiaozhang","192.168.18.176"); 即可
*/
initParameters.put("allow","");
// 设置初始化参数
bean.setInitParameters(initParameters);
return bean;
}
}
6 准备SQL语句
准备了简单的数据查询SQL语句
package com.xzzlx.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class JdbcController {
@Autowired
JdbcTemplate jdbcTemplate;
// 没有实体类,数据库中的东西可以使用Map获得
@GetMapping("/userList")
public List<Map<String, Object>> userList(){
String sql = "select * from win_database01.user";
List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql);
return list_maps;
}
@GetMapping("/updateUser")
public String addUser(){
String sql = "insert into win_database01.user(id, name, password)
values (6886, '小丫丫','123456')";
jdbcTemplate.update(sql);
return "update-ook";
}
@GetMapping("/updateUser/{id}")
public String updateUser(@PathVariable("id") Integer id){
String sql = "update win_database01.user set name = ?,password = ? where id = " + id;
Object[] objects = new Object[2];
objects[0] = "kuangshen";
objects[1] = "675822137";
jdbcTemplate.update(sql, objects);
return "updateUser-ookkkkkkk";
}
@GetMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable("id") Integer id){
String sql = "delete from win_database01.user where id =" + id;
jdbcTemplate.update(sql);
return "deleteUser-ook";
}
}
7 测试
启动SpringBoot主项目进行测试
package com.xzzlx;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Springboot04DataApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot04DataApplication.class, args);
}
}
7.1 打开后台日志地址
192.168.18.176:8080/druid
发现一个阿里已经写好了的日志监控后台
在5 准备好SQL语句中配置好的进行登录
账号:admin
密码:123456
整个日志界面是阿里已经帮我们写好了的,点击SQL监控,然后去另外打开个窗口执行SQL语句
7.2 打开访问地址
打开一个页面去测试我们的SQL语句
192.168.18.176:8080/userList
访问成功
此时回到我们SQL监控的窗口刷新,可以看到我们的Log日志
推荐一个up主,狂神说java,有问题可以评论,一起交流~~