• Springboot入门2-配置druid


    Druid是Java语言中最好的数据库连接池,在连接池之外,还提供了非常优秀的监控功能。

    下面来说明如何在 Spring Boot 中配置使用Druid

    1、添加Maven依赖 (或jar包)

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

    2、配置数据源相关信息

    ####################数据源配置####################
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/springsea?useUnicode=true&characterEncoding=utf-8
    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
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    spring.datasource.filters=stat,wall,log4j
    # 通过connectProperties属性来打开mergeSql功能(参数不同的sql合并统计)、慢SQL记录(执行时间长的sql)
    spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    # 合并多个DruidDataSource的监控数据
    #spring.datasource.useGlobalDataSourceStat=true

    详细配置参考:spring配置数据库连接池druid

    3、创建配置文件

    目前Spring Boot中默认支持的连接池有dbcp,dbcp2, tomcat, hikari三种连接池。 

    由于Druid暂时不在Spring Boot中的直接支持,故需要进行配置信息的定制。

    package com.xzh.config;
    
    import java.sql.SQLException;
    
    import javax.sql.DataSource;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import org.springframework.beans.factory.annotation.Value;
    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.Primary;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import com.alibaba.druid.support.http.StatViewServlet;
    import com.alibaba.druid.support.http.WebStatFilter;
    
    /**
     * Created by xiangzh on 2017/12/5.
     */
    @Configuration
    public class DruidConfig {
    
        private Logger logger = LoggerFactory.getLogger(DruidConfig.class);
    
        @Value("${spring.datasource.url}")
        private String dbUrl;
    
        @Value("${spring.datasource.username}")
        private String username;
    
        @Value("${spring.datasource.password}")
        private String password;
    
        @Value("${spring.datasource.driver-class-name}")
        private String driverClassName;
    
        @Value("${spring.datasource.initialSize}")
        private int initialSize;
    
        @Value("${spring.datasource.minIdle}")
        private int minIdle;
    
        @Value("${spring.datasource.maxActive}")
        private int maxActive;
    
        @Value("${spring.datasource.maxWait}")
        private int maxWait;
    
        @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
        private int timeBetweenEvictionRunsMillis;
    
        @Value("${spring.datasource.minEvictableIdleTimeMillis}")
        private int minEvictableIdleTimeMillis;
    
        @Value("${spring.datasource.validationQuery}")
        private String validationQuery;
    
        @Value("${spring.datasource.testWhileIdle}")
        private boolean testWhileIdle;
    
        @Value("${spring.datasource.testOnBorrow}")
        private boolean testOnBorrow;
    
        @Value("${spring.datasource.testOnReturn}")
        private boolean testOnReturn;
    
        @Value("${spring.datasource.filters}")
        private String filters;
    
        @Value("${spring.datasource.connectionProperties}") 
       private String connectionProperties; 
    
        @Primary
        @Bean(name = "dataSource")
        public DataSource dataSource() {
            DruidDataSource datasource = new DruidDataSource();
            datasource.setUrl(this.dbUrl);
            datasource.setUsername(username);
            datasource.setPassword(password);
            datasource.setDriverClassName(driverClassName); //configuration
            datasource.setInitialSize(initialSize);
            datasource.setMinIdle(minIdle);
            datasource.setMaxActive(maxActive);
            datasource.setMaxWait(maxWait);
            datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
            datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
            datasource.setValidationQuery(validationQuery);
            datasource.setTestWhileIdle(testWhileIdle);
            datasource.setTestOnBorrow(testOnBorrow);
            datasource.setTestOnReturn(testOnReturn);
            try {
                datasource.setFilters(filters);
            } catch (SQLException e) {
                logger.error("druid configuration initialization filter", e);
            }
            datasource.setConnectionProperties(connectionProperties);
            return datasource;
        }
    
        /**
         * 注册一个StatViewServlet * @return
         */
        @Bean
        public ServletRegistrationBean DruidStatViewServle2() {
            ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid333/*"); //添加初始化参数:initParams 
            /** 白名单,如果不配置或value为空,则允许所有 */
            servletRegistrationBean.addInitParameter("allow", "127.0.0.1,192.0.0.1"); /** 黑名单,与白名单存在相同IP时,优先于白名单 */
            servletRegistrationBean.addInitParameter("deny", "192.0.0.1"); /** 用户名 */
            servletRegistrationBean.addInitParameter("loginUsername", "xiangzhenhai"); /** 密码 */
            servletRegistrationBean.addInitParameter("loginPassword", "xzh335645"); /** 禁用页面上的“Reset All”功能 */
            servletRegistrationBean.addInitParameter("resetEnable", "false");
            return servletRegistrationBean;
        }
    
        /**
         * 注册一个:WebStatFilter * @return
         */
        @Bean
        public FilterRegistrationBean druidStatFilter2() {
            FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter()); /** 过滤规则 */
            filterRegistrationBean.addUrlPatterns("/*"); /** 忽略资源 */
            filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid333/*");
            return filterRegistrationBean;
        }
    }

    4、启动项目,查看druid监控

    参考:

     Spring Boot 使用 Druid 和监控配置

    Spring Boot Druid数据源配置

  • 相关阅读:
    .net com
    Json树递归Js查询Json父子节点
    Angular中使用$watch监听object属性值的变化
    教程
    JS格式化Thu May 12 2016 08:00:00 GMT+0800 (中国标准时间)
    js中获取时间new Date()详细介绍
    select默认空白问题。。
    angular先加载页面再执行事件,特别在动态生成id,然后做echarts等图表
    详解angularJs中自定义directive的数据交互
    Angularjs ng-table的使用(可以加button)以及angularjs学习资料
  • 原文地址:https://www.cnblogs.com/Jason-Xiang/p/7992370.html
Copyright © 2020-2023  润新知