Spring整合Durid数据源
一、导入依赖
<!-- Druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
二、写applicatio.yml配置Durid数据源
spring:
datasource:
username: root
password: 123456
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/first_test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
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,wa1l,1og4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSq1=true;druid.stat.slowSqlMi1lis=500
三、自定义配置Durid数据源,扩展更多功能
DruidConfig.java
package com.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 {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
System.out.println("@DataDruid");
return new DruidDataSource();
}
//开启后台监控
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");//此处url就是显示后台监控的url
//要登陆才能看监控
HashMap<String, String> map = new HashMap<>();
map.put("loginUsername","wang");
map.put("loginPassword","123");
map.put("allow","localhost");//允许本机访问
bean.setInitParameters(map);
return bean;
}
}