Druid坐标引入
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.15</version>
</dependency>
maven仓库Maven Repository: com.alibaba » druid (mvnrepository.com)
配置Druid数据源
spring:
datasource:
username: root
password: 123456
# 假如sql连接异常,有可能是时区原因 添加时区& serverTimezone=UTC
url: jdbc:mysql://localhost:3306/sqlstudy?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
# 配置druid数据源
type: com.alibaba.druid.pool.DruidDataSource
查看配置是否成功
application.yml新增配置项
spring:
datasource:
username: root
password: 123456
# 假如sql连接异常,有可能是时区原因 添加时区& serverTimezone=UTC
url: jdbc:mysql://localhost:3306/sqlstudy?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
# 配置druid数据源
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
配置了log4j,必须要先添加log4j依赖,否则springboot项目会报错
DruidConfig配置类
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;
/**
* @author tian
*/
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
/**
* 后台监控:web.xml ServletRegistrationBean
* springBoot内置了servlet容器 所以没有web.xml 替代方法:ServletRegistrationBean
* @return
*/
@Bean
public ServletRegistrationBean a(){
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");
// 允许谁可以访问 ""所有人可以访问 禁止谁访问initParameters.put("kkk","192.168.128.128");
initParameters.put("allow","");
// 设置初始化参数
bean.setInitParameters(initParameters);
return bean;
}
}
测试
登录成功
登录失败
开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 2 天,点击查看活动详情