中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

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

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

springBoot(12):集成Druid

發布時間:2020-07-18 02:54:08 來源:網絡 閱讀:3273 作者:我愛大金子 欄目:MySQL數據庫

一、添加依賴

<!--mybatis-開始-->
<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>1.2.0</version>
</dependency>
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
</dependency>
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId >druid</artifactId>
   <version>1.0.26</version>
</dependency>
<!--mybatis-結束-->

二、配置application.properties

##################################mysql數據源配置##################################
spring.datasource.url=jdbc:mysql://localhost/db_test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#druid連接池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

注意:其實到這里就可以正常使用了,但是如果想使用druid里的諸多屬性,則需要添加支持類

三、添加druid的支持類

package com.example.demo.utils.configuration.druid;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DatabaseDriver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;


/**
 * druid的支持類
 * @Author: 我愛大金子
 * @Description: druid的支持類
 * @Date: Created in 12:48 2017/6/20
 */
@Configuration
public class DruidConfiguration {
    @ConditionalOnClass(DruidDataSource.class)
    @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.alibaba.druid.pool.DruidDataSource", matchIfMissing = true)
    static class Druid extends DruidConfiguration {
        @Bean
        @ConfigurationProperties("spring.datasource.druid")
        public DruidDataSource dataSource(DataSourceProperties properties) {
            DruidDataSource druidDataSource = (DruidDataSource)
                    properties.initializeDataSourceBuilder().type(DruidDataSource.class).build();
            DatabaseDriver databaseDriver =
                    DatabaseDriver.fromJdbcUrl(properties.determineUrl());
            String validationQuery = databaseDriver.getValidationQuery();
            if (validationQuery != null) {
                druidDataSource.setValidationQuery(validationQuery);
            }
            return druidDataSource;
        }
    }
}

配置application.properties:

##################################mysql數據源配置##################################
spring.datasource.url=jdbc:mysql://localhost/db_test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#初始化連接大小
spring.datasource.druid.initial-size=8
#最小空閑連接數
spring.datasource.druid.min-idle=5
#最大連接數
spring.datasource.druid.max-active=10
#查詢超時時間
spring.datasource.druid.query-timeout=6000
#事務查詢超時時間
spring.datasource.druid.transaction-query-timeout=6000
#關閉空閑連接超時時間
spring.datasource.druid.remove-abandoned-timeout=1800

四、監控

4.1、配置servlet

package com.example.demo.utils.configuration.druid;

import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import com.alibaba.druid.support.http.StatViewServlet;

/**
 * 監控-配置servlet
 * @Author: 我愛大金子
 * @Description: 監控-servlet
 * @Date: Created in 12:50 2017/6/20
 */
@WebServlet(urlPatterns = { "/druid/*" }, initParams =
        { @WebInitParam(name = "loginUsername", value = "liuy"),
          @WebInitParam(name = "loginPassword", value = "123456") })
public class DruidStatViewServlet extends StatViewServlet {
    private static final long serialVersionUID = 1L;
}

4.2、配置filter

package com.example.demo.utils.configuration.druid;

import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import com.alibaba.druid.support.http.WebStatFilter;

/**
 * 監控-配置filter
 * @Author: 我愛大金子
 * @Description: 描述
 * @Date: Created in 12:51 2017/6/20
 */
@WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*", initParams = { @WebInitParam(name = "exclusions", value = "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*") })
public class DruidWebStatFilter extends WebStatFilter {
}


測試:訪問http://localhost:9090/druid/index.html 

springBoot(12):集成Druid

springBoot(12):集成Druid


注意:此時還沒有SQL監控與spring監控。


4.3、配置sql監控與spring監控

在application.properties文件中配置sql監控

#sql監控配置:filter類名:stat,config,encoding,logging
spring.datasource.druid.filters=stat


spring監控配置

第一步:新建一個配置文件,如:druid-bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop.xsd">

   <!-- 配置_Druid和Spring關聯監控配置 -->
   <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor"></bean>

   <!-- 方法名正則匹配攔截配置 -->
   <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
      <property name="patterns">
         <list>
            <value>com.example.demo.mapper.*</value>
         </list>
      </property>
   </bean>

   <aop:config proxy-target-class="true">
      <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
   </aop:config>
</beans>

第二步:在啟動類上加載druid-bean.xml文件

package com.example.demo;

import com.example.demo.utils.filter.CustomFilter;
import com.example.demo.utils.listener.CustomListener;
import com.example.demo.utils.servlet.CustomServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportResource;

import javax.servlet.DispatcherType;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.EnumSet;

@ServletComponentScan
@SpringBootApplication
@ImportResource(locations = { "classpath:druid-bean.xml" })
public class SpringbootDemo27Application {
   public static void main(String[] args) {
      SpringApplication.run(SpringbootDemo27Application.class, args);
   }
}

重啟服務,報異常:

 springBoot(12):集成Druid

解決:添加aop依賴

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

 

重啟服務


springBoot(12):集成Druid



springBoot(12):集成Druid



另一種實現方式

package com.liuy.demo.configuration;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DatabaseDriver;
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 com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

@Configuration
public class DruidConfiguration {
	
	@ConditionalOnClass(DruidDataSource.class)
    @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.alibaba.druid.pool.DruidDataSource", matchIfMissing = true)
    static class Druid extends DruidConfiguration {
        @Bean
        @ConfigurationProperties("spring.datasource.druid")
        public DruidDataSource dataSource(DataSourceProperties properties) {
            DruidDataSource druidDataSource = (DruidDataSource)properties.initializeDataSourceBuilder().type(DruidDataSource.class).build();
            DatabaseDriver databaseDriver = DatabaseDriver.fromJdbcUrl(properties.determineUrl());
            String validationQuery = databaseDriver.getValidationQuery();
            if (validationQuery != null) {
                druidDataSource.setValidationQuery(validationQuery);
            }
            return druidDataSource;
        }
    }
	
	@Bean
	public ServletRegistrationBean statViewServlet() {
		ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
		// IP白名單
		servletRegistrationBean.addInitParameter("allow", "127.0.0.1,192.168.1.83");
		// IP黑名單(優先級高于白名單)
		servletRegistrationBean.addInitParameter("deny", "192.168.1.100");
		// 控制臺管理用戶
		servletRegistrationBean.addInitParameter("loginUsername", "liuy");
		servletRegistrationBean.addInitParameter("loginPassword", "123456");
		// 是否能夠重置數據
		servletRegistrationBean.addInitParameter("resetEnable", "false");
		
		return servletRegistrationBean;
	}
	
	@Bean
	public FilterRegistrationBean statFilter() {
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
		// 添加過濾規則
		filterRegistrationBean.addUrlPatterns("/*");
		// 忽略過濾的格式
		filterRegistrationBean.addInitParameter("exclusions", "*.js,*.css,*.jpg,*.ico,/druid/*");
		
		return filterRegistrationBean;
	}
}

application.properties:

spring.profiles.active=dev
server.port=9090

##################################mysql數據源配置##################################
spring.datasource.url=jdbc:mysql://localhost/db_test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# druid連接池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 初始化大小,最小,最大
spring.datasource.druid.initial-size=5
spring.datasource.druid.minIdle=5
spring.datasource.druid.maxActive=20
# 獲取連接等待超時的時間(毫秒)
spring.datasource.druid.max-wait=60000
# 間隔多久進行一次檢測,檢測需要關閉的空閑連接(毫秒)
spring.datasource.druid.time-between-eviction-runs-millis=60000
# 一個連接在池中的最小生存時間(毫秒)
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
# 打開PSCache,并且指定每個連接上PSCache的大小
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
# 查詢超時時間
spring.datasource.druid.query-timeout=6000
# 事務查詢超時時間
spring.datasource.druid.transaction-query-timeout=6000
# 關閉空閑連接超時時間
spring.datasource.druid.remove-abandoned-timeout=1800
# sql監控配置:filter類名:stat,config,encoding,logging
spring.datasource.druid.filters=stat
# 通過connect-properties屬性來打開mergesql功能;慢查詢記錄
spring.datasource.druid.connect-properties.druid.stat.meergeSql=true;
spring.datasource.druid.connect-properties.druid.stat.slowSqlMillis=5000
# 合并多個druidDataSource的監控數據
#spring.datasource.druid.use-global-data-source-stat=true
##################################mybatis基于xml集成##################################
#掃包
mybatis.mapper-locations: classpath:mybatis/*.xml
#別名
mybatis.type-aliases-package: com.liuy.demo.pojo


向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

邢台县| 荆门市| 武定县| 林芝县| 崇州市| 东阿县| 崇礼县| 延安市| 三门县| 武安市| 含山县| 昆明市| 尚义县| 邢台市| 五大连池市| 城固县| 二连浩特市| 商水县| 桃江县| 四川省| 东方市| 紫云| 呼图壁县| 阿克陶县| 甘德县| 图木舒克市| 伊宁县| 剑川县| 万源市| 泉州市| 建平县| 永胜县| 海盐县| 哈密市| 大余县| 星座| 祁门县| 斗六市| 望奎县| 阳江市| 临潭县|