一、springboot 中注册 Servlet/Filter/Listener 的方式有两种,1 通过代码注册 ServletRegistrationBean、 FilterRegistrationBean 和 ServletListenerRegistrationBean 。

2 通过注解的方式,在 SpringBootApplication 上使用@ServletComponentScan 注解后,Servlet、Filter、Listener 可以直接通过 @WebServlet、@WebFilter、@WebListener 注解自动注册,无需其他代码。

二、配置springboot 项目使用Druid 数据源,好处就不多说了,百度一下很多。配置步骤,本机使用maven配置

2.1 引入依赖,完整的pom文件如下

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3. <modelVersion>4.0.</modelVersion>
  4. <groupId>com.huitong</groupId>
  5. <artifactId>demo1</artifactId>
  6. <packaging>jar</packaging>
  7. <version>1.0-SNAPSHOT</version>
  8. <name>demo1 Maven Webapp</name>
  9. <url>http://maven.apache.org</url>
  10.  
  11. <parent>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-parent</artifactId>
  14. <version>2.0..RELEASE</version>
  15. </parent>
  16.  
  17. <properties>
  18. <java.version>1.8</java.version>
  19. <mybatis.spring.boot.version>1.3.</mybatis.spring.boot.version>
  20. <springfox-swagger.version>2.8.</springfox-swagger.version>
  21. <swagger-bootstrap-ui.version>1.7.</swagger-bootstrap-ui.version>
  22. <druid.version>1.1.</druid.version>
  23.  
  24. </properties>
  25.  
  26. <dependencies>
  27.  
  28. <dependency>
  29. <groupId>com.alibaba</groupId>
  30. <artifactId>druid</artifactId>
  31. <version>${druid.version}</version>
  32. </dependency>
  33.  
  34. <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
  35. <dependency>
  36. <groupId>io.springfox</groupId>
  37. <artifactId>springfox-swagger2</artifactId>
  38. <version>${springfox-swagger.version}</version>
  39. </dependency>
  40.  
  41. <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
  42. <dependency>
  43. <groupId>io.springfox</groupId>
  44. <artifactId>springfox-swagger-ui</artifactId>
  45. <version>${springfox-swagger.version}</version>
  46. </dependency>
  47.  
  48. <!-- https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui -->
  49. <dependency>
  50. <groupId>com.github.xiaoymin</groupId>
  51. <artifactId>swagger-bootstrap-ui</artifactId>
  52. <version>${swagger-bootstrap-ui.version}</version>
  53. </dependency>
  54.  
  55. <dependency>
  56. <groupId>org.springframework.boot</groupId>
  57. <artifactId>spring-boot-starter-web</artifactId>
  58. </dependency>
  59.  
  60. <dependency>
  61. <groupId>org.springframework.boot</groupId>
  62. <artifactId>spring-boot-starter-test</artifactId>
  63. <scope>test</scope>
  64. </dependency>
  65.  
  66. <dependency>
  67. <groupId>mysql</groupId>
  68. <artifactId>mysql-connector-java</artifactId>
  69. </dependency>
  70.  
  71. <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
  72. <dependency>
  73. <groupId>org.mybatis.spring.boot</groupId>
  74. <artifactId>mybatis-spring-boot-starter</artifactId>
  75. <version>${mybatis.spring.boot.version}</version>
  76. </dependency>
  77.  
  78. <!--&lt;!&ndash; 添加缓存支持 &ndash;&gt;-->
  79. <!--<dependency>-->
  80. <!--<groupId>org.springframework.boot</groupId>-->
  81. <!--<artifactId>spring-boot-starter-cache</artifactId>-->
  82. <!--</dependency>-->
  83.  
  84. <!-- 添加 redis 缓存支持 -->
  85. <dependency>
  86. <groupId>org.springframework.boot</groupId>
  87. <artifactId>spring-boot-starter-data-redis</artifactId>
  88. </dependency>
  89.  
  90. <!-- 添加邮件支持 -->
  91. <dependency>
  92. <groupId>org.springframework.boot</groupId>
  93. <artifactId>spring-boot-starter-mail</artifactId>
  94. </dependency>
  95.  
  96. <dependency>
  97. <groupId>com.jayway.jsonpath</groupId>
  98. <artifactId>json-path</artifactId>
  99. </dependency>
  100.  
  101. <dependency>
  102. <groupId>org.projectlombok</groupId>
  103. <artifactId>lombok</artifactId>
  104. </dependency>
  105.  
  106. <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
  107. <dependency>
  108. <groupId>org.apache.commons</groupId>
  109. <artifactId>commons-lang3</artifactId>
  110. </dependency>
  111.  
  112. <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
  113. <dependency>
  114. <groupId>org.apache.httpcomponents</groupId>
  115. <artifactId>httpclient</artifactId>
  116. </dependency>
  117.  
  118. <!-- Spring boot 热启动依赖 -->
  119. <dependency>
  120. <groupId>org.springframework.boot</groupId>
  121. <artifactId>spring-boot-devtools</artifactId>
  122. <optional>true</optional>
  123. </dependency>
  124.  
  125. </dependencies>
  126.  
  127. <build>
  128. <finalName>demo1</finalName>
  129. <resources>
  130. <resource>
  131. <directory>src/main/resources</directory>
  132. <includes>
  133. <include>**/*.xml</include>
  134. <include>**/*.properties</include>
  135. </includes>
  136. </resource>
  137.  
  138. <resource>
  139. <directory>src/main/java</directory>
  140. <includes>
  141. <include>**/*.xml</include>
  142. <include>**/*.properties</include>
  143. </includes>
  144. </resource>
  145. </resources>
  146.  
  147. <!--spring boot maven的构造插件-->
  148. <plugins>
  149. <plugin>
  150. <groupId>org.springframework.boot</groupId>
  151. <artifactId>spring-boot-maven-plugin</artifactId>
  152. <configuration>
  153. <fork>true</fork>
  154. </configuration>
  155. </plugin>
  156.  
  157. <plugin>
  158. <groupId>org.apache.maven.plugins</groupId>
  159. <artifactId>maven-compiler-plugin</artifactId>
  160. <configuration>
  161. <source>${java.version}</source>
  162. <target>${java.version}</target>
  163. <testSource>${java.version}</testSource>
  164. <testTarget>${java.version}</testTarget>
  165. </configuration>
  166. </plugin>
  167.  
  168. </plugins>
  169. </build>
  170.  
  171. </project>

需要引入:mysql-connector-java,druid,

2.2 配置数据源 application.properties

  1. #数据库配置
  2. # 驱动配置信息
  3. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  4. spring.datasource.url=jdbc:mysql://localhost:3306/demo1?useUnicode=true&characterEncoding=UTF-8&useSSL=false&zeroDateTimeBehavior=convertToNull
  5. spring.datasource.username=root
  6. spring.datasource.password=test
  7. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  8.  
  9. # 连接池的配置信息
  10. # 初始化大小,最小,最大
  11. spring.datasource.initialSize=
  12. spring.datasource.minIdle=
  13. spring.datasource.maxActive=
  14.  
  15. # 配置获取连接等待超时的时间
  16. spring.datasource.maxWait=
  17. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  18. spring.datasource.timeBetweenEvictionRunsMillis=
  19.  
  20. # 配置一个连接在池中最小生存的时间,单位是毫秒
  21. spring.datasource.minEvictableIdleTimeMillis=
  22. spring.datasource.validationQuery=SELECT FROM DUAL
  23. spring.datasource.testWhileIdle=true
  24. spring.datasource.testOnBorrow=false
  25. spring.datasource.testOnReturn=false
  26.  
  27. # 打开PSCache,并且指定每个连接上PSCache的大小
  28. spring.datasource.poolPreparedStatements=true
  29. spring.datasource.maxPoolPreparedStatementPerConnectionSize=
  30. # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
  31. spring.datasource.filters=stat,wall
  32. # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
  33. spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=
  34.  
  35. #mybatis 配置
  36.  
  37. #扫描映射文件
  38. mybatis.mapper-locations=classpath*:com/huitong/**/mapper/*.xml

2.3 配置 web 监控,使用注解的方式注册 监控显示Servlet 和 采集web-jdbc关联监控的数据的Filter,

2.3.1 数据源配置

  1. import com.alibaba.druid.pool.DruidDataSource;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.context.annotation.Primary;
  8.  
  9. import javax.sql.DataSource;
  10. import java.sql.SQLException;
  11.  
  12. @Configuration
  13. public class DruidDBConfig {
  14.  
  15. private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);
  16.  
  17. @Value("${spring.datasource.url}")
  18. private String dbUrl;
  19.  
  20. @Value("${spring.datasource.username}")
  21. private String username;
  22.  
  23. @Value("${spring.datasource.password}")
  24. private String password;
  25.  
  26. @Value("${spring.datasource.driver-class-name}")
  27. private String driverClassName;
  28.  
  29. @Value("${spring.datasource.initialSize}")
  30. private int initialSize;
  31.  
  32. @Value("${spring.datasource.minIdle}")
  33. private int minIdle;
  34.  
  35. @Value("${spring.datasource.maxActive}")
  36. private int maxActive;
  37.  
  38. @Value("${spring.datasource.maxWait}")
  39. private int maxWait;
  40.  
  41. @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
  42. private int timeBetweenEvictionRunsMillis;
  43.  
  44. @Value("${spring.datasource.minEvictableIdleTimeMillis}")
  45. private int minEvictableIdleTimeMillis;
  46.  
  47. @Value("${spring.datasource.validationQuery}")
  48. private String validationQuery;
  49.  
  50. @Value("${spring.datasource.testWhileIdle}")
  51. private boolean testWhileIdle;
  52.  
  53. @Value("${spring.datasource.testOnBorrow}")
  54. private boolean testOnBorrow;
  55.  
  56. @Value("${spring.datasource.testOnReturn}")
  57. private boolean testOnReturn;
  58.  
  59. @Value("${spring.datasource.poolPreparedStatements}")
  60. private boolean poolPreparedStatements;
  61.  
  62. @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
  63. private int maxPoolPreparedStatementPerConnectionSize;
  64.  
  65. @Value("${spring.datasource.filters}")
  66. private String filters;
  67.  
  68. @Value("{spring.datasource.connectionProperties}")
  69. private String connectionProperties;
  70.  
  71. /**
  72. * @Bean 声明,DataSource 对象为 Spring 容器所管理;
  73. * @Primary 表示这里定义的DataSource将覆盖其他来源的DataSource。
  74. * StatFilter,用于统计监控信息。StatFilter的别名是stat。
  75. * 统计SQL信息,合并统计。mergeStat是的MergeStatFilter缩写。
  76. * 通过 DataSource 的属性<property name="filters" value="mergeStat" /> 或者
  77. * connectProperties属性来打开mergeSql功能 <property name="connectionProperties" value="druid.stat.mergeSql=true" />
  78. * StatFilter属性slowSqlMillis用来配置SQL慢的标准
  79. *
  80. * @return
  81. */
  82. @Bean
  83. @Primary
  84. public DataSource dataSource() {
  85. DruidDataSource datasource = new DruidDataSource();
  86. datasource.setUrl(dbUrl);
  87. datasource.setDriverClassName(driverClassName);
  88. datasource.setUsername(username);
  89. datasource.setPassword(password);
  90.  
  91. //configuration
  92. datasource.setInitialSize(initialSize);
  93. datasource.setMinIdle(minIdle);
  94. datasource.setMaxActive(maxActive);
  95. datasource.setMaxWait(maxWait);
  96. datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  97. datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  98. datasource.setValidationQuery(validationQuery);
  99. datasource.setTestWhileIdle(testWhileIdle);
  100. datasource.setTestOnBorrow(testOnBorrow);
  101. datasource.setTestOnReturn(testOnReturn);
  102. datasource.setPoolPreparedStatements(poolPreparedStatements);
  103. datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
  104. try {
  105. /**
  106. * 设置StatFilter,用于统计监控信息。
  107. * StatFilter的别名是stat
  108. *
  109. */
  110. datasource.setFilters(filters);
  111. } catch (SQLException e) {
  112. logger.error("druid configuration initialization filter : {0}",e);
  113. }
  114. datasource.setConnectionProperties(connectionProperties);
  115.  
  116. return datasource;
  117. }
  118.  
  119. }

2.3.2 通过注解的方式配置监控显示页面 Servlet

  1. import com.alibaba.druid.support.http.StatViewServlet;
  2.  
  3. import javax.servlet.annotation.WebInitParam;
  4. import javax.servlet.annotation.WebServlet;
  5.  
  6. /**
  7. * StatViewServlet用于展示Druid的统计信息。
  8. * 提供监控信息展示的html页面
  9. * 提供监控信息的JSON API
  10. *
  11. * 内置监控页面的首页是/druid/index.html
  12. *
  13. */
  14.  
  15. /**
  16. * @Webservlet
  17. * 有两个属性可以用来表示Servlet的访问路径,分别是value和urlPatterns。value和urlPatterns都是数组形式,
  18. * 表示我们可以把一个Servlet映射到多个访问路径,但是value和urlPatterns不能同时使用。
  19. *
  20. */
  21. @WebServlet(
  22. urlPatterns = {"/druid/*"},
  23. initParams = {
  24. @WebInitParam(name = "loginUsername", value = "admin"),
  25. @WebInitParam(name = "loginPassword", value = "test"),
  26. @WebInitParam(name = "resetEnable", value = "false")
  27. // @WebInitParam(name = "allow", value = "127.0.0.1")
  28. }
  29. )
  30. public class DruidStatViewServlet extends StatViewServlet {
  31. }

2.3.3 通过注解的方式配置采集Filter

  1. import com.alibaba.druid.support.http.WebStatFilter;
  2.  
  3. import javax.servlet.annotation.WebFilter;
  4. import javax.servlet.annotation.WebInitParam;
  5.  
  6. /**
  7. * WebStatFilter用于采集web-jdbc关联监控的数据。
  8. * 属性filterName声明过滤器的名称,可选
  9. * 属性urlPatterns指定要过滤 的URL模式,也可使用属性value来声明.(指定要过滤的URL模式是必选属性)
  10. */
  11.  
  12. @WebFilter(
  13. urlPatterns = "/demo1/*",
  14. initParams = {
  15. @WebInitParam(name = "exclusions",value = "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*")
  16. }
  17. )
  18. public class DruidStatFilter extends WebStatFilter {
  19. }

2.4 使应用开启扫描注册功能

  1. // 开启组件扫描和自动配置
  2. // mapper 扫描 mapper 接口
  3. @SpringBootApplication
  4. @MapperScan(basePackages = {"com.huitong.**.mapper"})
  5. @ServletComponentScan(basePackages = {"com.huitong.**.config"})
  6. public class Demo1Application {
  7.  
  8. public static void main(String[] args) {
  9. SpringApplication.run(Demo1Application.class, args);//负责启动引导应用程序
  10. }
  11. }

2.5 此时配置完成,如果应用搞完就可以测试了。启动应用后在浏览器中输入 http://localhost:8080/druid/index.html

通过登录即可看到监控信息

springboot 中使用Druid 数据源提供数据库监控的更多相关文章

  1. springboot中加入druid对sql进行监控

    springboot作为现在十分流行的框架,简化Spring应用的初始搭建以及开发过程,现在我们就使用springboot来进行简单的web项目搭建并对项目sql进行监控. 项目的搭建就省略了,spr ...

  2. Druid数据源对数据库访问密码加密好麻烦

    开发中,druid数据源对数据库密码进行了加密,每次切换数据库或者修改密码后,感觉很麻烦. 解决办法: 1.用工具类中的Java代码进行加解密. 需要用到com.alibaba.druid.filte ...

  3. springboot中实现多数据源

    springboot中实现多数据源 1.什么场景需要多数据源 业务读写分离 业务分库 业务功能模块拆分多库 2.常见的多数据源的方案 按照数据源分别把mapper和entity放到不同的package ...

  4. SpringBoot整合阿里Druid数据源及Spring-Data-Jpa

    SpringBoot整合阿里Druid数据源及Spring-Data-Jpa https://mp.weixin.qq.com/s?__biz=MzU0MDEwMjgwNA==&mid=224 ...

  5. springboot中使用druid和监控配置

    如果想要监控自己的项目的访问情况及查看配置信息,druid是一个很好的选择,可能你会问druid是什么?有什么用?优点是什么? Druid简介 Druid是阿里巴巴开源的数据库连接池,号称是Java语 ...

  6. Druid数据源SQL数据库与Spring监控

    Druid监控概要说明 为什么要监控? Druid是什么?德鲁伊 URL监控配置说明 配置步骤 步骤 配置 第一步 web.xml 配置 WebStatFilter 第二步 WebStatFilter ...

  7. Springboot中配置druid

    pom文件信息: <!--引入druid数据源--> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> ...

  8. SpringBoot中对于异常处理的提供的五种处理方式

    1.自定义错误页面 SpringBoot 默认的处理异常机制:SpringBoot默认的已经提供了一套处理异常的机制.一旦程序中出现了异常,SpringBoot会向/error的url发送请求.在Sp ...

  9. SpringBoot 集成 Mybatis 使用 Druid数据源 MySQL数据库

    思路: 1.创建项目 项目结构如下: 2.导入相应包 POM.xml文件如下: <?xml version="1.0" encoding="UTF-8"? ...

随机推荐

  1. Windows操作系统下的MySQL主从复制及读写分离[转]

    mysql主从复制配置   保证主库和从库数据库数据一致 mysql主库MASTER配置(在my.cnf中加入以下配置):log-bin=master-binbinlog-do-db=test #需要 ...

  2. win7下安装matlab后打开出错“error starting desktop”的解决办法

    在matlab快捷图标上右键,选择"还原以前的版本"--"兼容性"选项卡,在"以兼容模式运行这个程序"前面打勾,并选择"windo ...

  3. 好久不git这么多问题

    本来想把本地项目上传GitHub一下,打开gitbash, git init 之前配置过了 用户名和邮箱以及ssh等 $ git remote add origin https://github.co ...

  4. CentOS静默安装Oracle 11gR2(x64)

    环境 OS: CentOS 7.4; hosts: L134; IP: 192.168.1.134 DB: linux.x64_11gR2_database 安装依赖包 yum install -y ...

  5. POJ 3268 Bookshelf 2 动态规划法题解

    Description Farmer John recently bought another bookshelf for the cow library, but the shelf is gett ...

  6. 【shell】shell基础脚本合集

    1.向脚本传递参数 #!/bin/bash #功能:打印文件名与输入参数 #作者:OLIVER echo $0 #打印文件名 echo $1 #打印输入参数 执行结果: 2.在脚本中使用参数 #!/b ...

  7. MongoDB中的一些坑( 2.4.10 版本)

    http://www.jb51.net/article/62654.htm 1.MongoDB 数据库级锁 MongoDB的锁机制和一般关系数据库如 MySQL(InnoDB), Oracle 有很大 ...

  8. Linux的telent服务

    目前,在Win/Linux下telnet都很少用了,只是因为数据在传输的过程,未加密!不过在Linux下还是多用于端口探测,今天就来回顾曾经的telnet 1.介绍 Linux被广泛运用到各种服务器及 ...

  9. Linux下grub.cnf详解

    grub.conf跟系统启动项有关,对于重置密码.来说小case... 1.介绍    在Red Hat Linux7.2之后,默认的引导加载程序从LTLO变为GRUB.这个引导加载程序使用户能够选择 ...

  10. 从零開始学android&lt;AnalogClock与DigitalClock时钟组件.三十一.&gt;

    这两个组件比較交单,大家看下会使用即可了 XML文件配置 <span style="font-size:18px;"><RelativeLayout xmlns: ...