溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringBoot使用Druid數(shù)據(jù)源的配置方法

發(fā)布時(shí)間:2020-08-19 17:56:32 來源:腳本之家 閱讀:312 作者:crazy_bai 欄目:編程語言

Druid是阿里巴巴開源平臺(tái)上一個(gè)數(shù)據(jù)庫連接池實(shí)現(xiàn),它結(jié)合了C3P0、DBCP、PROXOOL等DB池的優(yōu)點(diǎn),同時(shí)加入了日志監(jiān)控,可以很好的監(jiān)控DB池連接和SQL的執(zhí)行情況,可以說是針對(duì)監(jiān)控而生的DB連接池(據(jù)說是目前最好的連接池)

一、依賴

為了測(cè)試,使用jdbcTemplate

<!-- jdbcTemplate -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- druid數(shù)據(jù)庫連接池 -->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.0.26</version>
</dependency>
<!-- mysql connector -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope>
</dependency>

二、Druid配置

druid.properties
#數(shù)據(jù)庫設(shè)置
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/uu_core?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
#--------------------------
# 下面為連接池的補(bǔ)充設(shè)置,應(yīng)用到上面所有數(shù)據(jù)源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=1
spring.datasource.maxActive=50
# 配置獲取連接等待超時(shí)的時(shí)間
spring.datasource.maxWait=60000
# 配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接,單位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打開PSCache,并且指定每個(gè)連接上PSCache的大小
spring.datasource.poolPreparedStatements=false
#spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置監(jiān)控統(tǒng)計(jì)攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計(jì),'wall'用于防火墻
spring.datasource.filters=stat,wall,log4j
# 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多個(gè)DruidDataSource的監(jiān)控?cái)?shù)據(jù)
#spring.datasource.useGlobalDataSourceStat=true

三、實(shí)例化Druid Datasource

package cn.aduu.config;
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 org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
/**
 * @author zh
 * @ClassName cn.aduu.config.DruidConfiguration
 * @Description
 */
@Configuration
@PropertySource(value = "classpath:druid.properties")
public class DruidConfiguration {
  @Bean(destroyMethod = "close", initMethod = "init")
  @ConfigurationProperties(prefix = "spring.datasource")
  public DataSource druidDataSource() {
    DruidDataSource druidDataSource = new DruidDataSource();
    return druidDataSource;
  }
  /**
   * 注冊(cè)一個(gè)StatViewServlet
   * @return
   */
  @Bean
  public ServletRegistrationBean druidStatViewServlet(){
    //org.springframework.boot.context.embedded.ServletRegistrationBean提供類的進(jìn)行注冊(cè).
    ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
    //添加初始化參數(shù):initParams
    //白名單:
    servletRegistrationBean.addInitParameter("allow","127.0.0.1");
    //IP黑名單 (存在共同時(shí),deny優(yōu)先于allow) : 如果滿足deny的話提示:Sorry, you are not permitted to view this page.
    servletRegistrationBean.addInitParameter("deny","192.168.1.73");
    //登錄查看信息的賬號(hào)密碼.
    servletRegistrationBean.addInitParameter("loginUsername","admin");
    servletRegistrationBean.addInitParameter("loginPassword","123456");
    //是否能夠重置數(shù)據(jù).
    servletRegistrationBean.addInitParameter("resetEnable","false");
    return servletRegistrationBean;
  }
  /**
   * 注冊(cè)一個(gè):filterRegistrationBean
   * @return
   */
  @Bean
  public FilterRegistrationBean druidStatFilter(){
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
    //添加過濾規(guī)則.
    filterRegistrationBean.addUrlPatterns("/*");
    //添加不需要忽略的格式信息.
    filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
    return filterRegistrationBean;
  }
}

四、監(jiān)控

訪問 http://localhost:8080/druid, 使用上面配置的賬號(hào)密碼。

SpringBoot使用Druid數(shù)據(jù)源的配置方法

SpringBoot使用Druid數(shù)據(jù)源的配置方法

五、測(cè)試

@RestController
public class HelloController{
  private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
  @Autowired
  private JdbcTemplate jdbcTemplate;
  @RequestMapping("hello")
  public List<Map<String, Object>> hello() {
    List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT user,password FROM mysql.user ", new Object[]{});
    return list;
  }
}

訪問 localhost:8080/hello

[
  {
    "user": "root",
    "password": "*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B"
  },
  {
    "user": "root",
    "password": "*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B"
  }
]

總結(jié)

以上所述是小編給大家介紹的SpringBoot使用Druid數(shù)據(jù)源,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI