1. 程式人生 > >Spring中Druid鏈接池的配置

Spring中Druid鏈接池的配置

initials 掃描 destroy hub 攔截 pre localhost 行程 filter

本文記錄了使用Druid的方法, 包括Spring和Spring boot中使用Druid的配置方法.

Spring中配置Druid連接池

以鏈接mysql為例

1 添加druid依賴

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>${version}</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.43</version>
</dependency>

2 在Spring配置中添加Druid相關配置

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
     <!-- 基本屬性 url、user、password -->
     <property name="driverClassName" value="${jdbc.driver}" />
     <property name="url" value="${jdbc_url}" />
     <property name="username" value="${jdbc_user}" />
     <property name="password" value="${jdbc_password}" />
     <!-- 配置監控統計攔截的filters -->
     <property name="filters" value="stat" />
     <!-- 配置初始化大小、最小、最大連接池數量 -->
     <property name="maxActive" value="20" />
     <property name="initialSize" value="1" />
     <property name="minIdle" value="1" />
     <!-- 配置獲取連接等待超時的時間 -->
     <property name="maxWait" value="60000" /> 
     <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 -->
     <property name="timeBetweenEvictionRunsMillis" value="60000" />
     <!-- 配置一個連接在池中最小生存的時間,單位是毫秒 -->
     <property name="minEvictableIdleTimeMillis" value="300000" />
     <property name="testWhileIdle" value="true" />
     <property name="testOnBorrow" value="false" />
     <property name="testOnReturn" value="false" />
     <!-- 打開PSCache,並且指定每個連接上PSCache的大小 -->
     <property name="poolPreparedStatements" value="true" />
     <property name="maxOpenPreparedStatements" value="20" />
</bean>

3 在web.xml中添加Druid相關配置

  <filter>
    <filter-name>DruidWebStatFilter</filter-name>
    <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
    <init-param>
      <param-name>exclusions</param-name>
      <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>DruidWebStatFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

然後運行程序訪問http://localhost:8080/druid即可

Spring boot中配置Druid連接池

首先添加pom依賴, 然後application.properties配置信息如下:

# 驅動配置信息  
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource  
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/mealsystem?useUnicode=true&characterEncoding=utf-8  
spring.datasource.username = root  
spring.datasource.password = 123456  
spring.datasource.driverClassName = com.mysql.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,log4j  
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

Spring boot的Druid監控設置

首先druid配置文件中需要有如下相關filter配置, 內置的Filter名字可參考這裏

spring.datasource.filters=stat,wall,log4j 

然後再註冊Servlet和Filter. 有兩種方法

方法一 使用代碼註冊Servlet和Filter

新建一個DruidConfiguration文件

@Configuration
public class DruidConfiguration {

    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        servletRegistrationBean.addUrlMappings("/druid/*");

        Map<String, String> initParameters = new HashMap<String, String>();
        initParameters.put("loginUsername", "admin");
        initParameters.put("loginPassword", "admin");
        initParameters.put("resetEnable", "false");

        servletRegistrationBean.setInitParameters(initParameters);

        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

}

然後運行程序訪問http://localhost:8080/druid即可

方法二 原生的servlet和filter方式

配置Servlet代碼

@WebServlet(
        urlPatterns = "/druid/*",
        initParams = {
                @WebInitParam(name = "loginUsername", value = "admin"),
                @WebInitParam(name = "loginPassword", value = "admin"),
                @WebInitParam(name = "resetEnable", value = "admin"),
        }
)
public class DruidStatViewServlet extends StatViewServlet {
}

配置filter

@WebFilter(
        filterName = "druidWebStatFilter",
        urlPatterns = "/*",
        initParams = {
                @WebInitParam(name = "exclusions", value = "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*")
        }
)
public class DruidWebStatFilter extends WebStatFilter {
}

然後在spring boot啟動類Application.java上加註解@ServletComponentScan 設置Servlet自動掃描.訪問http://localhost:8080/druid測試.

Spring中Druid鏈接池的配置