1. 程式人生 > 實用技巧 >SpringBoot整合Druid資料來源

SpringBoot整合Druid資料來源

1.匯入Druid依賴

<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid</artifactId>
     <version>1.1.21</version>
</dependency>

2.編寫application.yml配置檔案

spring:
  datasource:
    username: xxx
    password: xxx
    url: jdbc:mysql://localhost:3306/資料庫名?serverTimezone=UTC
&useUnicode=true&characterEncoding=utf-8&useSSL=true driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource #Spring Boot 預設是不注入這些屬性值的,需要自己繫結 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 依賴即可 filters: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

3.在application.yml裡配置Druid資料來源其他引數後並不會生效,我們需要編寫配置類,向容器裡注入元件

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import
org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.servlet.Filter; import javax.servlet.ServletRegistration; import javax.sql.DataSource; import java.util.HashMap; @Configuration public class DruidConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource druidDataSource(){ return new DruidDataSource(); } //後臺監控 @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("allow","localhost"); /**禁止誰能訪問 *initParameters.put("xxxx","xxxx"); */ initParameters.put("loginPassword","123456"); bean.setInitParameters(initParameters);;//設定初始化引數 return bean; } //filter @Bean public FilterRegistrationBean webStartFilter(){ FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>(); bean.setFilter(new WebStatFilter()); //可以過濾哪些請求 HashMap<String, String> initParamters = new HashMap<>(); initParamters.put("exclusion","*.js,*.css,/druid/*"); bean.setInitParameters(initParamters); return bean; } }

4.訪問localhost:8080/druid可以檢視監控資訊