最新消息:iOS编程开发交流群(6906921) ,Mac.Cocoa开发交流群(7758675) 欢迎iOS/macOS开发编程爱好及学习者加入!

Spring Boot配置阿里Druid数据源与统计监控

Java 天狐 13322浏览 0评论

1. Druid是什么?

Druid是Java语言中最好的数据库连接池。Druid能够提供强大的监控和扩展功能。

https://github.com/alibaba/druid

一.添加Maven依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.11</version>
</dependency>

二.配置数据源相关信息

application.properties和application.yml配置都是可以的,spring boot会默认读取两种文件,yml默认是没有的,可以直接新建。

当然写在application.properties中要有略微的区别,因为语法不一样。

下边的是yml语法写的application.yml配置。

spring:
  profiles: dev

  datasource:
    url: jdbc:mysql://192.168.215.233:3306/test?useUnicode=true&characterEncoding=UTF8&allowMultiQueries=true
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
    #已废弃
    #type: com.alibaba.druid.pool.DruidDataSource
    # 初始化大小,最小,最大
    initialSize: 5
    minIdle: 5
    maxActive: 20
    # 配置获取连接等待超时的时间
    maxWait: 60000
    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    timeBetweenEvictionRunsMillis: 60000
    # 配置一个连接在池中最小生存的时间,单位是毫秒
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    # 打开PSCache,并且指定每个连接上PSCache的大小
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    # 合并多个DruidDataSource的监控数据
    useGlobalDataSourceStat: true

application.properties中示例

# 数据库访问配置
# 主数据源,默认的
# 已废弃
#spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.MySQL.jdbc.Driver
spring.datasource.url=jdbc:MySQL://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root

# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
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
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
#spring.datasource.useGlobalDataSourceStat=true
#需要注意的是:spring.datasource.type旧的spring boot版本是不能识别的。

三.注入Druid数据源

注入数据源有两种方式。

一种@Bean("duridDatasource")这种注入,可以写在app.java种,也可以新建单独的类去实现。

package org.skyfox.spring_boot_demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;

import com.alibaba.druid.pool.DruidDataSource;
import javax.sql.DataSource;

@SpringBootApplication
@MapperScan("org.skyfox.spring_boot_demo.mapper")
////这行是为了避免扫描不到Druid的Servlet
@ServletComponentScan("org.skyfox.spring_boot_demo.config.druid")
public class App 
{
    public static void main( String[] args )
    {
    	SpringApplication.run(App.class);
    }
    
    @Bean("duridDatasource")
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource druidDataSource() {
    	return new DruidDataSource();
    }

}

再一种是新建类去实现EnvironmentAware接口和@Configuration@EnableTransactionManagement的方式注入druid数据源。

package org.skyfox.spring_boot_demo.config.druid;
import java.sql.SQLException;
 
import javax.sql.DataSource;
 
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;
 
import com.alibaba.druid.pool.DruidDataSource;
 
@Configuration
@EnableTransactionManagement
public class DataBaseConfiguration implements EnvironmentAware {
 
	 private RelaxedPropertyResolver propertyResolver;
 
	    @Override
	    public void setEnvironment(Environment env) {
	        this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
	    }
	    
	    @Bean(destroyMethod = "close", initMethod = "init")
	    public DataSource writeDataSource() throws SQLException {
	        System.out.println("注入druid!!!");
	        
	       
	        DruidDataSource dataSource = new DruidDataSource();
	        dataSource.setUrl(propertyResolver.getProperty("url"));
	        dataSource.setUsername(propertyResolver.getProperty("username"));//用户名
	        dataSource.setPassword(propertyResolver.getProperty("password"));//密码
	        dataSource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
	        dataSource.setInitialSize(Integer.parseInt(propertyResolver.getProperty("initialSize")));
	        dataSource.setMaxActive(Integer.parseInt(propertyResolver.getProperty("maxActive")));
	        dataSource.setMinIdle(Integer.parseInt(propertyResolver.getProperty("minIdle")));
	        dataSource.setMaxWait(Integer.parseInt(propertyResolver.getProperty("maxWait")));
	        dataSource.setTimeBetweenEvictionRunsMillis(Integer.parseInt(propertyResolver.getProperty("timeBetweenEvictionRunsMillis")));
	        dataSource.setMinEvictableIdleTimeMillis(Integer.parseInt(propertyResolver.getProperty("minEvictableIdleTimeMillis")));
	        dataSource.setValidationQuery(propertyResolver.getProperty("validationQuery"));
	        dataSource.setTestOnBorrow(Boolean.getBoolean(propertyResolver.getProperty("testOnBorrow")));
	        dataSource.setTestWhileIdle(Boolean.getBoolean(propertyResolver.getProperty("testWhileIdle")));
	        dataSource.setTestOnReturn(Boolean.getBoolean(propertyResolver.getProperty("testOnReturn")));
	        dataSource.setPoolPreparedStatements(Boolean.getBoolean(propertyResolver.getProperty("poolPreparedStatements")));
	        dataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(propertyResolver.getProperty("maxPoolPreparedStatementPerConnectionSize")));
	        //配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
	        dataSource.setFilters(propertyResolver.getProperty("filters"));
	        return dataSource;
	    }
 
}

 

四.配置监控统计功能

配置servlet有多种方式。web.xml 、注解 、代码。本文主要讲注解与代码方式,web.xml的原始方式在官方文档中可以查阅。

新建一个package,com.xxxxx.config.druid包,以下类都建在了config.druid包内。

Druid内置提供了一个StatViewServlet用于展示Druid的统计信息。

这个StatViewServlet的用途包括:提供监控信息展示的html页面,提供监控信息的JSON API(注意:使用StatViewServlet,建议使用druid 0.2.6以上版本。)

Druid内置提供一个StatFilter,用于统计监控信息。

1.基于注解模式的原生servlet

新建配置过滤器DruidStatFilter.java

package org.skyfox.spring_boot_demo.config.druid;

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监控视图配置,新建DruidStatViewServlet.java

package org.skyfox.spring_boot_demo.config.druid;
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=""),// IP白名单 (没有配置或者为空,则允许所有访问)  
//	    @WebInitParam(name="deny",value="127.0.0.1"),// IP黑名单 (存在共同时,deny优先于allow)  
	    @WebInitParam(name="loginUsername",value="admin"),// 用户名  
	    @WebInitParam(name="loginPassword",value="admin"),// 密码  
	    @WebInitParam(name="resetEnable",value="true")// 禁用HTML页面上的“Reset All”功能  
	}) 
	
public class DruidStatViewServlet extends StatViewServlet {
	private static final long serialVersionUID = 2359758657306626394L;
}

在APP.java中使用@Bean("duridDatasource")这种方法注入Druid数据源。

最后在App.java类上加上注解:

@ServletComponentScan("org.skyfox.spring_boot_demo.config.druid")

让spring能够扫描到我们自己编写的servlet和filter。

不添加 @ServletComponentScan 注解,访问druid页面就会404了。

然后启动项目后访问 http://127.0.0.1:8080/druid/  即可查看数据源及SQL统计等。

2.使用代码方式注册Servlet

如果配置了第一种方法,注释掉app.java中的@ServletComponentScan 以及druidDataSource()方法或者删除相关java文件。

新建DruidConfiguration.java

package org.skyfox.spring_boot_demo.config.druid;

import com.alibaba.druid.pool.DruidDataSource; 
import com.alibaba.druid.support.http.StatViewServlet; 
import com.alibaba.druid.support.http.WebStatFilter;

import javax.sql.DataSource;
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; 


@Configuration
//这里读取的是yml配置文件 也可以读取properties
@PropertySource(value = "classpath:application.yml")
public class DruidConfiguration {
	 @Bean(destroyMethod = "close", initMethod = "init") 
	 @ConfigurationProperties(prefix = "spring.datasource") 
	 public DataSource druidDataSource() { 
		 DruidDataSource druidDataSource = new DruidDataSource(); 
                 return druidDataSource; 
	} 
	 /**
	   * 注册一个StatViewServlet
	   * @return
	 */
	 @Bean public ServletRegistrationBean druidStatViewServlet(){ 
		 //org.springframework.boot.context.embedded.ServletRegistrationBean提供类的进行注册. 
		 ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*"); 
		 //添加初始化参数:initParams //白名单: 
		 servletRegistrationBean.addInitParameter("allow",""); 
		 //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
//		 servletRegistrationBean.addInitParameter("deny",""); //登录查看信息的账号密码. 
		 servletRegistrationBean.addInitParameter("loginUsername","admin"); 
		 servletRegistrationBean.addInitParameter("loginPassword","123456"); 
		 //是否能够重置数据. 
		 servletRegistrationBean.addInitParameter("resetEnable","false"); 
		 return servletRegistrationBean; 
	 }
    /**
     * 注册一个:filterRegistrationBean
     * @return
     */
	 @Bean public FilterRegistrationBean druidStatFilter(){
		 FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
		 //添加过滤规则.
		 filterRegistrationBean.addUrlPatterns("/*"); 
		 //添加不需要忽略的格式信息. 
		 filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); 
		 return filterRegistrationBean;
	 }
}

然后启动项目后访问 http://127.0.0.1:8080/druid/  即可查看数据源及SQL统计等。

转载请注明:天狐博客 » Spring Boot配置阿里Druid数据源与统计监控

微信 OR 支付宝 扫描二维码
为天狐 打赏
非常感谢你的支持,哥会继续努力!
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址