springboot 中使用Druid 数据源提供数据库监控
一、springboot 中注册 Servlet/Filter/Listener 的方式有两种,1 通过代码注册 ServletRegistrationBean、 FilterRegistrationBean 和 ServletListenerRegistrationBean 。
2 通过注解的方式,在 SpringBootApplication 上使用@ServletComponentScan 注解后,Servlet、Filter、Listener 可以直接通过 @WebServlet、@WebFilter、@WebListener 注解自动注册,无需其他代码。
二、配置springboot 项目使用Druid 数据源,好处就不多说了,百度一下很多。配置步骤,本机使用maven配置
2.1 引入依赖,完整的pom文件如下
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.</modelVersion>
- <groupId>com.huitong</groupId>
- <artifactId>demo1</artifactId>
- <packaging>jar</packaging>
- <version>1.0-SNAPSHOT</version>
- <name>demo1 Maven Webapp</name>
- <url>http://maven.apache.org</url>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.0..RELEASE</version>
- </parent>
- <properties>
- <java.version>1.8</java.version>
- <mybatis.spring.boot.version>1.3.</mybatis.spring.boot.version>
- <springfox-swagger.version>2.8.</springfox-swagger.version>
- <swagger-bootstrap-ui.version>1.7.</swagger-bootstrap-ui.version>
- <druid.version>1.1.</druid.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>${druid.version}</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-swagger2</artifactId>
- <version>${springfox-swagger.version}</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-swagger-ui</artifactId>
- <version>${springfox-swagger.version}</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui -->
- <dependency>
- <groupId>com.github.xiaoymin</groupId>
- <artifactId>swagger-bootstrap-ui</artifactId>
- <version>${swagger-bootstrap-ui.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- </dependency>
- <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>${mybatis.spring.boot.version}</version>
- </dependency>
- <!--<!– 添加缓存支持 –>-->
- <!--<dependency>-->
- <!--<groupId>org.springframework.boot</groupId>-->
- <!--<artifactId>spring-boot-starter-cache</artifactId>-->
- <!--</dependency>-->
- <!-- 添加 redis 缓存支持 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-redis</artifactId>
- </dependency>
- <!-- 添加邮件支持 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-mail</artifactId>
- </dependency>
- <dependency>
- <groupId>com.jayway.jsonpath</groupId>
- <artifactId>json-path</artifactId>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>
- <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- </dependency>
- <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- </dependency>
- <!-- Spring boot 热启动依赖 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-devtools</artifactId>
- <optional>true</optional>
- </dependency>
- </dependencies>
- <build>
- <finalName>demo1</finalName>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <includes>
- <include>**/*.xml</include>
- <include>**/*.properties</include>
- </includes>
- </resource>
- <resource>
- <directory>src/main/java</directory>
- <includes>
- <include>**/*.xml</include>
- <include>**/*.properties</include>
- </includes>
- </resource>
- </resources>
- <!--spring boot maven的构造插件-->
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <configuration>
- <fork>true</fork>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <source>${java.version}</source>
- <target>${java.version}</target>
- <testSource>${java.version}</testSource>
- <testTarget>${java.version}</testTarget>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </project>
需要引入:mysql-connector-java,druid,
2.2 配置数据源 application.properties
- #数据库配置
- # 驱动配置信息
- spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
- spring.datasource.url=jdbc:mysql://localhost:3306/demo1?useUnicode=true&characterEncoding=UTF-8&useSSL=false&zeroDateTimeBehavior=convertToNull
- spring.datasource.username=root
- spring.datasource.password=test
- spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- # 连接池的配置信息
- # 初始化大小,最小,最大
- spring.datasource.initialSize=
- spring.datasource.minIdle=
- spring.datasource.maxActive=
- # 配置获取连接等待超时的时间
- spring.datasource.maxWait=
- # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
- spring.datasource.timeBetweenEvictionRunsMillis=
- # 配置一个连接在池中最小生存的时间,单位是毫秒
- spring.datasource.minEvictableIdleTimeMillis=
- spring.datasource.validationQuery=SELECT FROM DUAL
- spring.datasource.testWhileIdle=true
- spring.datasource.testOnBorrow=false
- spring.datasource.testOnReturn=false
- # 打开PSCache,并且指定每个连接上PSCache的大小
- spring.datasource.poolPreparedStatements=true
- spring.datasource.maxPoolPreparedStatementPerConnectionSize=
- # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
- spring.datasource.filters=stat,wall
- # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
- spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=
- #mybatis 配置
- #扫描映射文件
- mybatis.mapper-locations=classpath*:com/huitong/**/mapper/*.xml
2.3 配置 web 监控,使用注解的方式注册 监控显示Servlet 和 采集web-jdbc关联监控的数据的Filter,
2.3.1 数据源配置
- import com.alibaba.druid.pool.DruidDataSource;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.context.annotation.Primary;
- import javax.sql.DataSource;
- import java.sql.SQLException;
- @Configuration
- public class DruidDBConfig {
- private Logger logger = LoggerFactory.getLogger(DruidDBConfig.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.poolPreparedStatements}")
- private boolean poolPreparedStatements;
- @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
- private int maxPoolPreparedStatementPerConnectionSize;
- @Value("${spring.datasource.filters}")
- private String filters;
- @Value("{spring.datasource.connectionProperties}")
- private String connectionProperties;
- /**
- * @Bean 声明,DataSource 对象为 Spring 容器所管理;
- * @Primary 表示这里定义的DataSource将覆盖其他来源的DataSource。
- * StatFilter,用于统计监控信息。StatFilter的别名是stat。
- * 统计SQL信息,合并统计。mergeStat是的MergeStatFilter缩写。
- * 通过 DataSource 的属性<property name="filters" value="mergeStat" /> 或者
- * connectProperties属性来打开mergeSql功能 <property name="connectionProperties" value="druid.stat.mergeSql=true" />
- * StatFilter属性slowSqlMillis用来配置SQL慢的标准
- *
- * @return
- */
- @Bean
- @Primary
- public DataSource dataSource() {
- DruidDataSource datasource = new DruidDataSource();
- datasource.setUrl(dbUrl);
- datasource.setDriverClassName(driverClassName);
- datasource.setUsername(username);
- datasource.setPassword(password);
- //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);
- datasource.setPoolPreparedStatements(poolPreparedStatements);
- datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
- try {
- /**
- * 设置StatFilter,用于统计监控信息。
- * StatFilter的别名是stat
- *
- */
- datasource.setFilters(filters);
- } catch (SQLException e) {
- logger.error("druid configuration initialization filter : {0}",e);
- }
- datasource.setConnectionProperties(connectionProperties);
- return datasource;
- }
- }
2.3.2 通过注解的方式配置监控显示页面 Servlet
- import com.alibaba.druid.support.http.StatViewServlet;
- import javax.servlet.annotation.WebInitParam;
- import javax.servlet.annotation.WebServlet;
- /**
- * StatViewServlet用于展示Druid的统计信息。
- * 提供监控信息展示的html页面
- * 提供监控信息的JSON API
- *
- * 内置监控页面的首页是/druid/index.html
- *
- */
- /**
- * @Webservlet
- * 有两个属性可以用来表示Servlet的访问路径,分别是value和urlPatterns。value和urlPatterns都是数组形式,
- * 表示我们可以把一个Servlet映射到多个访问路径,但是value和urlPatterns不能同时使用。
- *
- */
- @WebServlet(
- urlPatterns = {"/druid/*"},
- initParams = {
- @WebInitParam(name = "loginUsername", value = "admin"),
- @WebInitParam(name = "loginPassword", value = "test"),
- @WebInitParam(name = "resetEnable", value = "false")
- // @WebInitParam(name = "allow", value = "127.0.0.1")
- }
- )
- public class DruidStatViewServlet extends StatViewServlet {
- }
2.3.3 通过注解的方式配置采集Filter
- import com.alibaba.druid.support.http.WebStatFilter;
- import javax.servlet.annotation.WebFilter;
- import javax.servlet.annotation.WebInitParam;
- /**
- * WebStatFilter用于采集web-jdbc关联监控的数据。
- * 属性filterName声明过滤器的名称,可选
- * 属性urlPatterns指定要过滤 的URL模式,也可使用属性value来声明.(指定要过滤的URL模式是必选属性)
- */
- @WebFilter(
- urlPatterns = "/demo1/*",
- initParams = {
- @WebInitParam(name = "exclusions",value = "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*")
- }
- )
- public class DruidStatFilter extends WebStatFilter {
- }
2.4 使应用开启扫描注册功能
- // 开启组件扫描和自动配置
- // mapper 扫描 mapper 接口
- @SpringBootApplication
- @MapperScan(basePackages = {"com.huitong.**.mapper"})
- @ServletComponentScan(basePackages = {"com.huitong.**.config"})
- public class Demo1Application {
- public static void main(String[] args) {
- SpringApplication.run(Demo1Application.class, args);//负责启动引导应用程序
- }
- }
2.5 此时配置完成,如果应用搞完就可以测试了。启动应用后在浏览器中输入 http://localhost:8080/druid/index.html
通过登录即可看到监控信息
springboot 中使用Druid 数据源提供数据库监控的更多相关文章
- springboot中加入druid对sql进行监控
springboot作为现在十分流行的框架,简化Spring应用的初始搭建以及开发过程,现在我们就使用springboot来进行简单的web项目搭建并对项目sql进行监控. 项目的搭建就省略了,spr ...
- Druid数据源对数据库访问密码加密好麻烦
开发中,druid数据源对数据库密码进行了加密,每次切换数据库或者修改密码后,感觉很麻烦. 解决办法: 1.用工具类中的Java代码进行加解密. 需要用到com.alibaba.druid.filte ...
- springboot中实现多数据源
springboot中实现多数据源 1.什么场景需要多数据源 业务读写分离 业务分库 业务功能模块拆分多库 2.常见的多数据源的方案 按照数据源分别把mapper和entity放到不同的package ...
- SpringBoot整合阿里Druid数据源及Spring-Data-Jpa
SpringBoot整合阿里Druid数据源及Spring-Data-Jpa https://mp.weixin.qq.com/s?__biz=MzU0MDEwMjgwNA==&mid=224 ...
- springboot中使用druid和监控配置
如果想要监控自己的项目的访问情况及查看配置信息,druid是一个很好的选择,可能你会问druid是什么?有什么用?优点是什么? Druid简介 Druid是阿里巴巴开源的数据库连接池,号称是Java语 ...
- Druid数据源SQL数据库与Spring监控
Druid监控概要说明 为什么要监控? Druid是什么?德鲁伊 URL监控配置说明 配置步骤 步骤 配置 第一步 web.xml 配置 WebStatFilter 第二步 WebStatFilter ...
- Springboot中配置druid
pom文件信息: <!--引入druid数据源--> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> ...
- SpringBoot中对于异常处理的提供的五种处理方式
1.自定义错误页面 SpringBoot 默认的处理异常机制:SpringBoot默认的已经提供了一套处理异常的机制.一旦程序中出现了异常,SpringBoot会向/error的url发送请求.在Sp ...
- SpringBoot 集成 Mybatis 使用 Druid数据源 MySQL数据库
思路: 1.创建项目 项目结构如下: 2.导入相应包 POM.xml文件如下: <?xml version="1.0" encoding="UTF-8"? ...
随机推荐
- Windows操作系统下的MySQL主从复制及读写分离[转]
mysql主从复制配置 保证主库和从库数据库数据一致 mysql主库MASTER配置(在my.cnf中加入以下配置):log-bin=master-binbinlog-do-db=test #需要 ...
- win7下安装matlab后打开出错“error starting desktop”的解决办法
在matlab快捷图标上右键,选择"还原以前的版本"--"兼容性"选项卡,在"以兼容模式运行这个程序"前面打勾,并选择"windo ...
- 好久不git这么多问题
本来想把本地项目上传GitHub一下,打开gitbash, git init 之前配置过了 用户名和邮箱以及ssh等 $ git remote add origin https://github.co ...
- CentOS静默安装Oracle 11gR2(x64)
环境 OS: CentOS 7.4; hosts: L134; IP: 192.168.1.134 DB: linux.x64_11gR2_database 安装依赖包 yum install -y ...
- POJ 3268 Bookshelf 2 动态规划法题解
Description Farmer John recently bought another bookshelf for the cow library, but the shelf is gett ...
- 【shell】shell基础脚本合集
1.向脚本传递参数 #!/bin/bash #功能:打印文件名与输入参数 #作者:OLIVER echo $0 #打印文件名 echo $1 #打印输入参数 执行结果: 2.在脚本中使用参数 #!/b ...
- MongoDB中的一些坑( 2.4.10 版本)
http://www.jb51.net/article/62654.htm 1.MongoDB 数据库级锁 MongoDB的锁机制和一般关系数据库如 MySQL(InnoDB), Oracle 有很大 ...
- Linux的telent服务
目前,在Win/Linux下telnet都很少用了,只是因为数据在传输的过程,未加密!不过在Linux下还是多用于端口探测,今天就来回顾曾经的telnet 1.介绍 Linux被广泛运用到各种服务器及 ...
- Linux下grub.cnf详解
grub.conf跟系统启动项有关,对于重置密码.来说小case... 1.介绍 在Red Hat Linux7.2之后,默认的引导加载程序从LTLO变为GRUB.这个引导加载程序使用户能够选择 ...
- 从零開始学android<AnalogClock与DigitalClock时钟组件.三十一.>
这两个组件比較交单,大家看下会使用即可了 XML文件配置 <span style="font-size:18px;"><RelativeLayout xmlns: ...