(1)导入相关maven依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.2</version>
</dependency>
(2)application.yml中配置druid
spring:
datasource:
name: bs
data-username: root
data-password: 123456
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/billsystem?characterEncoding=UTF-8
type: com.alibaba.druid.pool.DruidDataSource
#下面都是一些参数设置,详细含义可以看官方文档
initialSize: 5
minIdle: 2
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
#配置监控统计的拦截功能,stat,监控统计,wall,防御sql注入,log4j,日志记录
filters: stat,wall,log4j
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
需要注意的,我们在上面因为使用到了log4j功能,所以导入相关依赖,不然就会报错
我们再次引入log4j的依赖。(有时候也会因为编码问题,在对yml编译后乱码无法识别,我们就需要把注释去掉,或者修改一下编码情况。这里不是指上面的错误,而且是特殊情况)
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
(3)配置druid的config配置类
package com.billsystem.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;
import java.util.Map;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
//后台监控
@Bean
public ServletRegistrationBean toBean(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
//配置后台账号密码
Map<String,String> map = new HashMap<>();
//用户名和密码的key是不可以更改的
map.put("loginUsername","admin");
map.put("loginPassword","123456");
//允许什么可以进入
map.put("allow","");
//配置不可以进入
map.put("deny","192.168.0.1");
//设置初始化参数
bean.setInitParameters(map);
return bean;
}
}
(4)监控展示
我们在启动服务器之后,在浏览器里面输入127.0.0.1/druid
就会自动跳到登录界面,我们再输入我们配置好的账号密码就可以进入了
我们同时再进行几条sql语句的执行,看看有没有监控到
网友评论