Java SpringBoot Druid

Environment

SpringBoot -V2.1.8
>>Win10
>>IDEA-2019.2.2
>>Java8

1、Github代码提交记录

SpringBoot项目配置阿里云Druid数据源监控

2、Maven工程引入pom依赖

  1. <!--引入阿里的druid数据源-->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>druid</artifactId>
  5. <version>1.1.20</version>
  6. </dependency>

3、SpringBoot中添加配置类

DruidConfig.java

```java package com.fcant.shop.config;

import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; 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 javax.sql.DataSource; import java.util.Arrays; import java.util.HashMap; import java.util.Map;

/**

  • DruidConfig *
  • @author Fcscanf@樊乘乘
  • @description
  • @date 上午 11:18 2018-08-14 */ @Configuration public class DruidConfig {

    /**

    • 注册Druid *
    • @param
    • @return
    • @author Fcscanf@樊乘乘
    • @date 上午 11:24 2018-08-14 */ @ConfigurationProperties(prefix = “spring.datasource”) @Bean public DataSource druid() { return new DruidDataSource(); }

      //配置Druid监控

      /**

    • 配置Druid管理后台的Servlet *
    • @param
    • @return
    • @author Fcscanf@樊乘乘
    • @date 上午 11:25 2018-08-14 / @Bean public ServletRegistrationBean statViewServlet() { ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), “/druid/“); //配置数据后台管理员 Map initParams = new HashMap<>(); initParams.put(“loginUsername”, “admin”); initParams.put(“loginPassword”, “509165”); //值为空则默认允许所有人访问 initParams.put(“allow”, “”); //指定用户不能登录 initParams.put(“deny”, “101.132.167.127”); bean.setInitParameters(initParams); return bean; }

      /**

    • 配置Druid后台的监控Filter *
    • @param
    • @return
    • @author Fcscanf@樊乘乘
    • @date 上午 11:25 2018-08-14 / @Bean public FilterRegistrationBean webStatFilter() { FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); Map initParams = new HashMap<>(); initParams.put(“exclusions”, “.js,.css,/druid/“); bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList(“/*”)); return bean; } }
  1. <a name="O96Q4"></a>
  2. ## 4、application.yml进行配置
  3. ```yaml
  4. spring:
  5. datasource:
  6. username: root
  7. password: 123456
  8. url: jdbc:mysql:///ssm?serverTimezone=UTC
  9. driver-class-name: com.mysql.cj.jdbc.Driver
  10. type: com.alibaba.druid.pool.DruidDataSource

5、项目目录结构

image.png

6、运行结果示意图

A.项目路径添加请求druid进入登录界面

image.png

B.进入项目的数据库监控管理

image.png