最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

如何在SpringBoot 中使用 Druid 數(shù)據(jù)庫(kù)連接池

 更新時(shí)間:2021年03月19日 17:14:00   作者:水貨程序員  
這篇文章主要介紹了SpringBoot 中使用 Druid 數(shù)據(jù)庫(kù)連接池的實(shí)現(xiàn)步驟,幫助大家更好的理解和學(xué)習(xí)使用SpringBoot,感興趣的朋友可以了解下

Druid是阿里開(kāi)源的一款數(shù)據(jù)庫(kù)連接池,除了常規(guī)的連接池功能外,它還提供了強(qiáng)大的監(jiān)控和擴(kuò)展功能。這對(duì)沒(méi)有做數(shù)據(jù)庫(kù)監(jiān)控的小項(xiàng)目有很大的吸引力。

下列步驟可以讓你無(wú)腦式的在SpringBoot2.x中使用Druid。

1.Maven中的pom文件

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid</artifactId>
	<version>1.1.14</version>
</dependency>
<dependency>
	<groupId>log4j</groupId>
	<artifactId>log4j</artifactId>
	<version>1.2.17</version>
</dependency>

使用 Spring Boot-2.x時(shí),如果未引入log4j,在配置 Druid 時(shí),會(huì)遇到Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Priority的報(bào)錯(cuò)。因?yàn)镾pring Boot默認(rèn)使用的是log4j2。

2.SpringBoot 配置文件

下面是一個(gè)完整的yml文件的,其中使用mybatis作為數(shù)據(jù)庫(kù)訪(fǎng)問(wèn)框架

server:
 servlet:
 context-path: /
 session:
  timeout: 60m
 port: 8080

spring:
 datasource:
 url: jdbc:mysql://127.0.0.1:9080/hospital?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
 username: root
 password: root
 # 環(huán)境 dev|test|pro
 profiles:
  active: dev
 driver-class-name: com.mysql.cj.jdbc.Driver

 ########################## druid配置 ##########################
 type: com.alibaba.druid.pool.DruidDataSource
 # 初始化大小,最小,最大 
 initialSize: 5
 minIdle: 1
 maxActive: 20
  # 配置獲取連接等待超時(shí)的時(shí)間 
 maxWait: 60000
 # 配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接,單位是毫秒 
 timeBetweenEvictionRunsMillis: 60000
 # 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒 
 minEvictableIdleTimeMillis: 300000
 # 校驗(yàn)SQL,Oracle配置 validationQuery=SELECT 1 FROM DUAL,如果不配validationQuery項(xiàng),則下面三項(xiàng)配置無(wú)用 
 validationQuery: SELECT 1 FROM DUAL
 testWhileIdle: true
 testOnBorrow: false
 testOnReturn: false
 # 打開(kāi)PSCache,并且指定每個(gè)連接上PSCache的大小 
 poolPreparedStatements: true
 maxPoolPreparedStatementPerConnectionSize: 20
 # 配置監(jiān)控統(tǒng)計(jì)攔截的filters,去掉后監(jiān)控界面sql無(wú)法統(tǒng)計(jì),'wall'用于防火墻 
 filters: stat,wall,log4j
 # 通過(guò)connectProperties屬性來(lái)打開(kāi)mergeSql功能;慢SQL記錄 
 connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
 # 合并多個(gè)DruidDataSource的監(jiān)控?cái)?shù)據(jù) 
 useGlobalDataSourceStat: true
 
# Mybatis配置
mybatis:
 mapperLocations: classpath:mapper/*.xml,classpath:mapper/extend/*.xml
 configuration:
 map-underscore-to-camel-case: true
 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3.配置Druid數(shù)據(jù)源實(shí)例

由于Druid暫時(shí)不在Spring Boot中的直接支持,故需要進(jìn)行配置信息的定制:

SpringBoot中的配置信息無(wú)法再Druid中直接生效,需要在Spring容器中實(shí)現(xiàn)一個(gè)DataSource實(shí)例。

import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
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 com.alibaba.druid.pool.DruidDataSource;

@Configuration
public class DruidDBConfig {
	private Logger logger = Logger.getLogger(this.getClass());	//log4j日志

	@Value("${spring.datasource.url}")
	private String dbUrl;

	@Value("${spring.datasource.username}")
	private String username;

	@Value("${spring.datasource.password}")
	private String password;

	@Value("${spring.datasource.driver-class-name}")
	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實(shí)例
	@Primary // 在同樣的DataSource中,首先使用被標(biāo)注的DataSource
	public DataSource dataSource() {
		DruidDataSource datasource = new DruidDataSource();

		datasource.setUrl(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);
			logger.error("druid configuration initialization filter", e);
			e.printStackTrace();
		}
		datasource.setConnectionProperties(connectionProperties);

		return datasource;
	}

}

4.過(guò)濾器和Servlet

還需要實(shí)現(xiàn)一個(gè)過(guò)濾器和Servlet,用于訪(fǎng)問(wèn)統(tǒng)計(jì)頁(yè)面。

過(guò)濾器

import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import com.alibaba.druid.support.http.WebStatFilter;
@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
 initParams={
 @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//忽略資源
 }
)
public class DruidStatFilter extends WebStatFilter {
 }

Servlet

import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
 
import com.alibaba.druid.support.http.StatViewServlet;
 
@WebServlet(urlPatterns="/druid/*",
 initParams={
   @WebInitParam(name="allow",value="127.0.0.1,192.168.163.1"),// IP白名單(沒(méi)有配置或者為空,則允許所有訪(fǎng)問(wèn))
   @WebInitParam(name="deny",value="192.168.1.73"),// IP黑名單 (存在共同時(shí),deny優(yōu)先于allow)
   @WebInitParam(name="loginUsername",value="admin"),// 用戶(hù)名
   @WebInitParam(name="loginPassword",value="admin"),// 密碼
   @WebInitParam(name="resetEnable",value="false")// 禁用HTML頁(yè)面上的“Reset All”功能
})
public class DruidStatViewServlet extends StatViewServlet {
	private static final long serialVersionUID = -2688872071445249539L;
 
}

5.使用@ServletComponentScan注解,

使得剛才創(chuàng)建的Servlet,F(xiàn)ilter能被訪(fǎng)問(wèn),SpringBoot掃描并注冊(cè)。

@SpringBootApplication()
@MapperScan("cn.china.mytestproject.dao")
//添加servlet組件掃描,使得Spring能夠掃描到我們編寫(xiě)的servlet和filter
@ServletComponentScan
public class MytestprojectApplication {
 public static void main(String[] args) {
 SpringApplication.run(MytestprojectApplication.class, args);
 } 
}

6.Dao層

接著Dao層代碼的實(shí)現(xiàn),可以使用mybatis,或者JdbcTemplate等。此處不舉例。

7.運(yùn)行

訪(fǎng)問(wèn)http://localhost:8080/druid/login.html地址即可打開(kāi)登錄頁(yè)面,賬號(hào)在之前的Servlet代碼中。

至此完成。

要了解更多,訪(fǎng)問(wèn):https://github.com/alibaba/druid

以上就是SpringBoot 中使用 Druid 數(shù)據(jù)庫(kù)連接池的實(shí)現(xiàn)步驟的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot 中使用 Druid 數(shù)據(jù)庫(kù)連接池的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Ubuntu快速安裝jdk的教程

    Ubuntu快速安裝jdk的教程

    這篇文章主要為大家詳細(xì)介紹了Ubuntu快速安裝jdk的教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • SPFA算法的實(shí)現(xiàn)原理及其應(yīng)用詳解

    SPFA算法的實(shí)現(xiàn)原理及其應(yīng)用詳解

    SPFA算法,全稱(chēng)為Shortest?Path?Faster?Algorithm,是求解單源最短路徑問(wèn)題的一種常用算法,本文就來(lái)聊聊它的實(shí)現(xiàn)原理與簡(jiǎn)單應(yīng)用吧
    2023-05-05
  • Java注解之Repeatable解讀

    Java注解之Repeatable解讀

    這篇文章主要介紹了Java注解之Repeatable,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • Java簡(jiǎn)單實(shí)現(xiàn)銀行ATM系統(tǒng)

    Java簡(jiǎn)單實(shí)現(xiàn)銀行ATM系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了Java簡(jiǎn)單實(shí)現(xiàn)銀行ATM系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • Java實(shí)現(xiàn)時(shí)間動(dòng)態(tài)顯示方法匯總

    Java實(shí)現(xiàn)時(shí)間動(dòng)態(tài)顯示方法匯總

    這篇文章主要介紹了Java實(shí)現(xiàn)時(shí)間動(dòng)態(tài)顯示方法匯總,很實(shí)用的功能,需要的朋友可以參考下
    2014-08-08
  • SpringMVC如何獲取表單數(shù)據(jù)(radio和checkbox)

    SpringMVC如何獲取表單數(shù)據(jù)(radio和checkbox)

    這篇文章主要介紹了SpringMVC如何獲取表單數(shù)據(jù)(radio和checkbox)的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • java解析JT808協(xié)議的實(shí)現(xiàn)代碼

    java解析JT808協(xié)議的實(shí)現(xiàn)代碼

    這篇文章主要介紹了java解析JT808協(xié)議的實(shí)現(xiàn)代碼,需要的朋友可以參考下
    2020-03-03
  • Java 添加文本框到PPT幻燈片過(guò)程解析

    Java 添加文本框到PPT幻燈片過(guò)程解析

    這篇文章主要介紹了Java 添加文本框到PPT幻燈片過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09
  • Java 遍歷 String 字符串所有字符的操作

    Java 遍歷 String 字符串所有字符的操作

    這篇文章主要介紹了Java 遍歷 String 字符串所有字符的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-10-10
  • SpringData整合ElasticSearch實(shí)現(xiàn)CRUD的示例代碼(超詳細(xì))

    SpringData整合ElasticSearch實(shí)現(xiàn)CRUD的示例代碼(超詳細(xì))

    本文主要介紹了SpringData整合ElasticSearch實(shí)現(xiàn)CRUD的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07

最新評(píng)論

绩溪县| 安义县| 改则县| 称多县| 庆云县| 定结县| 商洛市| 屯留县| 清水河县| 南充市| 定边县| 习水县| 古蔺县| 潮安县| 明溪县| 桐乡市| 清河县| 成武县| 秭归县| 哈尔滨市| 竹北市| 枞阳县| 文水县| 六安市| 松潘县| 濮阳市| 梅河口市| 娄烦县| 西华县| 涿州市| 舞钢市| 武安市| 阜新市| 安新县| 上饶县| 芒康县| 正宁县| 晋中市| 肇庆市| 昌平区| 衡阳市|