码迷,mamicode.com
首页 > 编程语言 > 详细

Spring配置Druid详细说明

时间:2019-08-09 19:28:48      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:web监控   select   views   sources   时间   作用   ble   strong   nal   

**简单直接,上代码,开封即食**

  • ***yml文件内容配置***
 1 # 数据源配置
 2 spring:
 3     datasource:
 4         type: com.alibaba.druid.pool.DruidDataSource
 5         driverClassName: com.mysql.cj.jdbc.Driver
 6         druid:
 7             # 主库数据源
 8             master:
 9                 url: jdbc:mysql://****
10                 username: ****
11                 password: ****
12             # 从库数据源
13             slave:
14                 # 从数据源开关/默认关闭
15                 enabled: false
16                 url: 
17                 username: 
18                 password: 
19             # 初始连接数
20             initialSize: 5
21             # 最小连接池数量
22             minIdle: 10
23             # 最大连接池数量
24             maxActive: 20
25             # 配置获取连接等待超时的时间
26             maxWait: 60000
27             # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
28             timeBetweenEvictionRunsMillis: 60000
29             # 配置一个连接在池中最小生存的时间,单位是毫秒
30             minEvictableIdleTimeMillis: 300000
31             # 配置一个连接在池中最大生存的时间,单位是毫秒
32             maxEvictableIdleTimeMillis: 900000
33             # 配置检测连接是否有效
34             validationQuery: SELECT 1 FROM DUAL
35             testWhileIdle: true
36             testOnBorrow: false
37             testOnReturn: false
38             webStatFilter: 
39                 enabled: true
40             statViewServlet:
41                 enabled: true
42                 # 设置白名单,不填则允许所有访问
43                 allow:
44                 url-pattern: /monitor/druid/*
45             filter:
46                 stat:
47                     enabled: true
48                     # 慢SQL记录
49                     log-slow-sql: true
50                     slow-sql-millis: 1000
51                     merge-sql: true
52                 wall:
53                     config:
54                         multi-statement-allow: true

 

  • ***DruidConfig文件***
  1 import java.io.IOException;
  2 import java.util.HashMap;
  3 import java.util.Map;
  4 import javax.servlet.Filter;
  5 import javax.servlet.FilterChain;
  6 import javax.servlet.ServletException;
  7 import javax.servlet.ServletRequest;
  8 import javax.servlet.ServletResponse;
  9 import javax.sql.DataSource;
 10 import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
 11 import org.springframework.boot.context.properties.ConfigurationProperties;
 12 import org.springframework.boot.web.servlet.FilterRegistrationBean;
 13 import org.springframework.context.annotation.Bean;
 14 import org.springframework.context.annotation.Configuration;
 15 import org.springframework.context.annotation.Primary;
 16 import com.alibaba.druid.pool.DruidDataSource;
 17 import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
 18 import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
 19 import com.alibaba.druid.util.Utils;
 20 import com.heater.common.enums.DataSourceType;
 21 import com.heater.framework.config.properties.DruidProperties;
 22 import com.heater.framework.datasource.DynamicDataSource;
 23 
 24 /**
 25  * druid 配置多数据源
 26  */
 27 @Configuration
 28 public class DruidConfig
 29 {
 30     @Bean
 31     @ConfigurationProperties("spring.datasource.druid.master")
 32     public DataSource masterDataSource(DruidProperties druidProperties)
 33     {
 34         DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
 35         return druidProperties.dataSource(dataSource);
 36     }
 37 
 38     @Bean
 39     @ConfigurationProperties("spring.datasource.druid.slave")
 40     @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
 41     public DataSource slaveDataSource(DruidProperties druidProperties)
 42     {
 43         DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
 44         return druidProperties.dataSource(dataSource);
 45     }
 46 
 47     @Bean(name = "dynamicDataSource")
 48     @Primary
 49     public DynamicDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource)
 50     {
 51         Map<Object, Object> targetDataSources = new HashMap<>();
 52         targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
 53         targetDataSources.put(DataSourceType.SLAVE.name(), slaveDataSource);
 54         return new DynamicDataSource(masterDataSource, targetDataSources);
 55     }
 56 
 57     /**
 58      * 去除监控页面底部的广告
 59      */
 60     @SuppressWarnings({ "rawtypes", "unchecked" })
 61     @Bean
 62     @ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true")
 63     public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties)
 64     {
 65         // 获取web监控页面的参数
 66         DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
 67         // 提取common.js的配置路径
 68         String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
 69         String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
 70         final String filePath = "support/http/resources/js/common.js";
 71         // 创建filter进行过滤
 72         Filter filter = new Filter()
 73         {
 74             @Override
 75             public void init(javax.servlet.FilterConfig filterConfig) throws ServletException
 76             {
 77             }
 78             @Override
 79             public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
 80                     throws IOException, ServletException
 81             {
 82                 chain.doFilter(request, response);
 83                 // 重置缓冲区,响应头不会被重置
 84                 response.resetBuffer();
 85                 // 获取common.js
 86                 String text = Utils.readFromResource(filePath);
 87                 // 正则替换banner, 除去底部的广告信息
 88                 text = text.replaceAll("<a.*?banner\"></a><br/>", "");
 89                 text = text.replaceAll("powered.*?shrek.wang</a>", "");
 90                 response.getWriter().write(text);
 91             }
 92             @Override
 93             public void destroy()
 94             {
 95             }
 96         };
 97         FilterRegistrationBean registrationBean = new FilterRegistrationBean();
 98         registrationBean.setFilter(filter);
 99         registrationBean.addUrlPatterns(commonJsPattern);
100         return registrationBean;
101     }
102 }

 

  • ***DruidProperties文件***
 1 import org.springframework.beans.factory.annotation.Value;
 2 import org.springframework.context.annotation.Configuration;
 3 import com.alibaba.druid.pool.DruidDataSource;
 4 
 5 /**
 6  * druid 配置属性
 7  */
 8 @Configuration
 9 public class DruidProperties
10 {
11     @Value("${spring.datasource.druid.initialSize}")
12     private int initialSize;
13 
14     @Value("${spring.datasource.druid.minIdle}")
15     private int minIdle;
16 
17     @Value("${spring.datasource.druid.maxActive}")
18     private int maxActive;
19 
20     @Value("${spring.datasource.druid.maxWait}")
21     private int maxWait;
22 
23     @Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}")
24     private int timeBetweenEvictionRunsMillis;
25 
26     @Value("${spring.datasource.druid.minEvictableIdleTimeMillis}")
27     private int minEvictableIdleTimeMillis;
28 
29     @Value("${spring.datasource.druid.maxEvictableIdleTimeMillis}")
30     private int maxEvictableIdleTimeMillis;
31 
32     @Value("${spring.datasource.druid.validationQuery}")
33     private String validationQuery;
34 
35     @Value("${spring.datasource.druid.testWhileIdle}")
36     private boolean testWhileIdle;
37 
38     @Value("${spring.datasource.druid.testOnBorrow}")
39     private boolean testOnBorrow;
40 
41     @Value("${spring.datasource.druid.testOnReturn}")
42     private boolean testOnReturn;
43 
44     public DruidDataSource dataSource(DruidDataSource datasource)
45     {
46         /** 配置初始化大小、最小、最大 */
47         datasource.setInitialSize(initialSize);
48         datasource.setMaxActive(maxActive);
49         datasource.setMinIdle(minIdle);
50 
51         /** 配置获取连接等待超时的时间 */
52         datasource.setMaxWait(maxWait);
53 
54         /** 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 */
55         datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
56 
57         /** 配置一个连接在池中最小、最大生存的时间,单位是毫秒 */
58         datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
59         datasource.setMaxEvictableIdleTimeMillis(maxEvictableIdleTimeMillis);
60 
61         /**
62          * 用来检测连接是否有效的sql,要求是一个查询语句,常用select ‘x‘。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。
63          */
64         datasource.setValidationQuery(validationQuery);
65         /** 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 */
66         datasource.setTestWhileIdle(testWhileIdle);
67         /** 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 */
68         datasource.setTestOnBorrow(testOnBorrow);
69         /** 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 */
70         datasource.setTestOnReturn(testOnReturn);
71         return datasource;
72     }
73 }

 

Spring配置Druid详细说明

标签:web监控   select   views   sources   时间   作用   ble   strong   nal   

原文地址:https://www.cnblogs.com/bangpenggao/p/11328958.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!