如今有點搞不懂這些寫博客的,就不能本身測試下嗎。搜篇 spring boot 配置 Druid鏈接池
,瀏覽了幾篇好像沒一篇可行的。css
由於版本迭代有問題能夠理解,可是這些人提供的方法 都不是這個緣由java
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.16</version>
</dependency>
複製代碼
這裏坑比較多,很容易出問題。mysql
# 驅動配置信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/test1?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password =
spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver
#鏈接池的配置信息
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
複製代碼
spring.datasource.urlgit
serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
複製代碼
若是 url 的配置不添加 serverTimezone=UTC
會報如上錯誤github
spring.datasource.driverClassNameweb
Loading class 'com.mysql.jdbc.Driver'. This is deprecated. The new driver class is 'com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
複製代碼
這裏很容易看懂,應該是版本的問題。將之前的spring
com.mysql.jdbc.Driver
複製代碼
替換成sql
com.mysql.cj.jdbc.Driver
複製代碼
spring.datasource.filtersbash
Caused by: org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource.druid' to javax.sql.DataSource at org.springframework.boot.context.properties.bind.Binder.handleBindError(Binder.java:250)
複製代碼
這裏我搜出來不少博客都是以下配置的app
spring.druid.filters=stat,wall,log4j
複製代碼
這也是個坑,將 log4j 去掉。改爲以下配置
spring.datasource.filters=stat,wall
複製代碼
你們都知道,spring boot 後面版本不支持配置文件中的配置,其實也能夠本身測一測。配置完運行後全是空的,都沒起做用。因此要去 java 代碼中配置 datasource 。並不須要將全部屬性都定義出來,用到那些定義那些便可,下面是個人。
package com.kstar.kxiaoju.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.sql.SQLException;
/**
* Created by guozhaohui628@gmail.com on 2018/12/17
* Description:
*/
@Configuration
public class DruidDBConfig {
private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);
@Value("${spring.datasource.url}")
private String dbUrl;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driverClassName}")
private String driverClassName;
@Value("${spring.datasource.initialSize}")
private int initialSize;
@Value("${spring.datasource.minIdle}")
private int minIdle;
@Value("${spring.datasource.maxActive}")
private int maxActive;
@Value("${spring.datasource.maxWait}")
private int maxWait;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.validationQuery}")
private String validationQuery;
@Value("${spring.datasource.testWhileIdle}")
private boolean testWhileIdle;
@Value("${spring.datasource.testOnBorrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.testOnReturn}")
private boolean testOnReturn;
@Value("${spring.datasource.poolPreparedStatements}")
private boolean poolPreparedStatements;
@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize;
@Value("${spring.datasource.filters}")
private String filters;
@Value("${spring.datasource.connectionProperties}")
private String connectionProperties;
@Bean //聲明其爲Bean實例
@Primary //在一樣的DataSource中,首先使用被標註的DataSource
public DataSource dataSource(){
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(this.dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
//configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
logger.error("druid configuration initialization filter", e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
}
複製代碼
這幾個註解的意思: DruidDBConfig類被@Configuration標註,用做配置信息; DataSource對象被@Bean聲明,爲Spring容器所管理, @Primary表示這裏定義的DataSource將覆蓋其餘來源的DataSource。 (複製別的博客)
package com.kstar.kxiaoju.config;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
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 java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Created by guozhaohui628@gmail.com on 2018/12/14
* Description:
*/
@Configuration
public class DruidConfig {
/**
* 配置druid監控
* 配置一個管理後臺的servlet
* 訪問地址:http://localhost:8080/druid/
* @return
*/
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String, String> initParameters = new HashMap<String, String>();
initParameters.put("loginUsername", "admin");//屬性見:com.alibaba.druid.support.http.ResourceServlet
initParameters.put("loginPassword", "123456");
initParameters.put("allow", "");//默認容許全部
initParameters.put("deny", "");
bean.setInitParameters(initParameters);
return bean;
}
/**
* 配置一個web監控的filter
* @return
*/
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean filterBean = new FilterRegistrationBean();
filterBean.setFilter(new WebStatFilter());
filterBean.setUrlPatterns(Arrays.asList("/*"));
Map<String, String> initParameters = new HashMap<String, String>();
initParameters.put("exclusions", "*.js,*.css,/druid/*");//屬性見:com.alibaba.druid.support.http.WebStatFilter
filterBean.setInitParameters(initParameters);
return filterBean;
}
}
複製代碼
package com.kstar.kxiaoju;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Created by guozhaohui628@gmail.com on 2018/12/17
* Description:
*/
@RestController
public class A {
@Autowired
private DataSource dataSource;
@RequestMapping("/dataSource")
public String dataSource() {
try {
System.out.println("dataSource = "+dataSource);
Connection conn = dataSource.getConnection();
System.out.println("conn = "+conn);
return "success";
} catch (SQLException e) {
e.printStackTrace();
}
return "end.";
}
}
複製代碼
能夠自行測試下,我這邊沒問題。