springBoot(12):集成Druid-成都快上网建站

springBoot(12):集成Druid

一、添加依赖

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:空间域名、网络空间、营销软件、网站建设、克拉玛依网站维护、网站推广。



   org.mybatis.spring.boot
   mybatis-spring-boot-starter
   1.2.0


   MySQL
   mysql-connector-java
   runtime


   com.alibaba
   druid
   1.0.26

二、配置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




   
   

   
   
      
         
            com.example.demo.mapper.*
         
      
   

   
      
   

第二步:在启动类上加载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依赖


   org.springframework.boot
   spring-boot-starter-aop

 

重启服务

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

文章题目:springBoot(12):集成Druid
当前网址:http://kswjz.com/article/pshpeg.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流