导包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-bom</artifactId>
<version>2.13.3</version>
</dependency>
配置yaml:配置数据库用户名密码
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/
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
配置类
@Configuration
public class DruidConfig {
//配置数据源
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
}
//durid数据源监控
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
HashMap<String, String> map = new HashMap<>();
//后台登陆账号密码
map.put("loginUsername", "admin");
map.put("loginPassword", "123456");
//后台谁可以访问
map.put("allow", "");
//设置初始化参数,map必须是<string,string>,源码中规定的
bean.setInitParameters(map);
return bean;
}
//配置过滤器bean,反正都是xxxRefistrationBean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>(new WebStatFilter());
HashMap<String, String> map = new HashMap<>();
map.put("extensions", "*.js,*.css");
bean.setInitParameters(map);
return bean;
}
}