前詹:數據源的集中比較
目前常用的數據源主要有c3p0、dbcp、proxool、druid,先來說說他們
Spring 推薦使用dbcp;
Hibernate 推薦使用c3p0和proxool
1:BCP:apache
DBCP(DataBase connection pool)數據庫連接池。是apache上的一個 java連接池項目,也是 tomcat使用的連接池組件。單獨使用dbcp需要3個包:common-dbcp.jar,common-pool.jar,common-collections.jar由於建立數據庫連接是一個非常耗時耗資源的行爲,所以通過連接池預先同數據庫建立一些連接,放在內存中,應用程序需要建立數據庫連接時直接到連接池中申請一個就行,用完後再放回去。dbcp沒有自動的去回收空閒連接的功能。
2: C3P0:
C3P0是一個開源的jdbc連接池,它實現了數據源和jndi綁定,支持jdbc3規範和jdbc2的標準擴展。c3p0是異步操作的,緩慢的jdbc操作通過幫助進程完成。擴展這些操作可以有效的提升性能。目前使用它的開源項目有Hibernate,Spring等。c3p0有自動回收空閒連接功能。
3: Proxool:Sourceforge
Proxool是一種Java數據庫連接池技術。是sourceforge下的一個開源項目,這個項目提供一個健壯、易用的連接池,最爲關鍵的是這個連接池提供監控的功能,方便易用,便於發現連接泄漏的情況。
綜合來說,穩定性是dbcp >= c3p0 > proxool
後來阿里巴巴的druid開源了,可以是前無古人後無來者,最強沒有之一,十分穩定,在大併發中表現十分好,德魯伊提供的這個監控組件,非常的便利,所有sql的監控,運行效率等等都能看到。
第一步:創建springboot項目的時候勾選
Web -- Spring Web, SQL-- JDBC API , SQL -- MySQL Driver 這三個選項
第二步:添加相關pom依賴
<!--引入Druid數據源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.18</version>
</dependency>
<!--導入配置文件處理器,配置文件進行綁定就會有提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
第三步:單獨拎出druid 的 datasource 數據源配置
datasource.yml 配置文件內容:
spring:
datasource:
username: root
password: sgl520
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/sgl_db
type: com.alibaba.druid.pool.DruidDataSource
# 數據源其他配置
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,去掉後監控界面sql無法統計,'wall'用於防火牆
filters: stat,wall
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
第四步:自定義druid 的 DataSource 組件 添加進容器
DruidConfig.java的代碼內容:
/**
*@ClassName DruidConfig
*@Description TODO 數據源Druid 配置化類
*@Author Ni Klaus
*@Date 2019/10/8 0008 下午 17:08
*@Version 1.0
*/
/*** 應爲我們是讀取單獨配置的datasource.yml 數據源配置文件 所以需要指定去 classpath:datasource.yml
文件裏面找 prefix = "spring.datasource" 再綁定到 DruidDataSource的屬性上去
而 @PropertySource 註解 又不支持 讀取.yml類型的配置文件,所以我這裏自定義了一個 YamlPropertySourceFactory
類,去讓 @PropertySource 註解 可以識別 .yml類型的配置文件
具體實現可以看我的另一篇博客:https://blog.csdn.net/sgl520lxl/article/details/102139764
裏面的(拓展:) 部分是怎麼實現的。*/
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:datasource.yml")
@Configuration
public class DruidConfig {
//根據配置文件綁定屬性,生成 DruidDataSource 組件 注入到ioc容器
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的監控
//1、配置一個管理後臺的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");//druid 後臺登錄名
initParams.put("loginPassword","123456");//druid 後臺登錄密碼
initParams.put("allow","");//默認就是允許所有訪問
initParams.put("deny","192.168.15.21");//拒絕的ip
bean.setInitParameters(initParams);
return bean;
}
//2、配置一個web監控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
//放行靜態文件和druid
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
YamlPropertySourceFactory.java 的代碼內容:
/**
*@ClassName YamlPropertySourceFactory
*@Description TODO 重寫 PropertySourceFactory 的 createPropertySource 使 @PropertySource 註解支持讀取 .yml類型的配置文件
*@Author Ni Klaus
*@Date 2019/10/8 0008 下午 17:53
*@Version 1.0
*/
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
// for ignoreResourceNotFound
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException)
throw (FileNotFoundException) e.getCause();
throw e;
}
}
}
第五步:啓動項目訪問druid的後臺地址
使用上面代碼裏面配置的賬號密碼登錄
initParams.put("loginUsername","admin");//druid 後臺登錄名
initParams.put("loginPassword","123456");//druid 後臺登錄密碼
就可以看到druid的視圖頁面了!
本教程項目demo源碼地址:https://github.com/Hak-L/sping-boot-with-druid