SpringBoot之使用Druid连接池,SQL监控和spring监控
项目结构
1.引入maven依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
2.在application.properties配置文件中加入druid配置
### mysql ###
spring.datasource.url=jdbc:mysql://localhost:3306/lw_test?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver ### mybatis ###
mybatis.mapper-locations=classpath:mybatis/*.xml ### durid ###
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
# 校验SQL,Oracle配置 spring.datasource.validationQuery=SELECT 1 FROM DUAL,如果不配validationQuery项,则下面三项配置无用
spring.datasource.validationQuery=SELECT 'x'
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
spring.datasource.useGlobalDataSourceStat=true ### log4j ###
log4j.rootLogger=DEBUG,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppenderlog4j.appender.Console.layout=org.apache.log4j.PatternLayout
og4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache=INFO
3.配置webServlet
package com.lw.coodydruid.servlet; import com.alibaba.druid.support.http.StatViewServlet; import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet; @WebServlet(urlPatterns = "/druid/*",
initParams = {
// @WebInitParam(name="allow",value="172.16.10.128,127.0.0.1"),// IP白名单 (没有配置或者为空,则允许所有访问)
// @WebInitParam(name="deny",value="172.16.10.129"),// IP黑名单 (存在共同时,deny优先于allow)
@WebInitParam(name = "loginUsername", value = "admin"),// 用户名
@WebInitParam(name = "loginPassword", value = "123456"),// 密码
@WebInitParam(name = "resetEnable", value = "false")// 禁用HTML页面上的“Reset All”功能
})
public class DruidServlet extends StatViewServlet { private static final long serialVersionUID = 1L; }
4.配置webFitler
package com.lw.coodydruid.filter; import com.alibaba.druid.support.http.WebStatFilter; import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam; @WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*",
initParams = {
@WebInitParam(name = "exclusions", value = "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*") // 忽略资源
})
public class DruidFilter extends WebStatFilter { }
5.在springboot启动类上,加上注解@ServletComponentScan,扫描filter和servlet
package com.lw.coodydruid; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.ImportResource; @SpringBootApplication
@ServletComponentScan
@ImportResource(locations = { "classpath:druid-bean.xml" })
public class CoodyDruidApplication { public static void main(String[] args) {
SpringApplication.run(CoodyDruidApplication.class, args);
} }
6.此处为手动初始化DataSource,也可以采用spring boot自动配置功能
package com.lw.coodydruid.configuration; import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component; import javax.sql.DataSource;
import java.sql.SQLException; /**
* @Classname DruidConfigration
* @Description 手动初始化DataSource
* @Date 2019/11/5 8:48
* @Created by lw
*/
@Component
public class DruidConfigration { @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;
@Value("${spring.datasource.useGlobalDataSourceStat}")
private boolean useGlobalDataSourceStat; @Bean
@Primary //在同样的DataSource中,首先使用被标注的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);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
datasource.setUseGlobalDataSourceStat(useGlobalDataSourceStat);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
System.err.println("druid configuration initialization filter: " + e);
}
datasource.setConnectionProperties(connectionProperties); return datasource;
} }
7.spring监控之方法名正则匹配拦截配置druid-bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 配置_Druid和Spring关联监控配置 -->
<bean id="druid-stat-interceptor"
class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor"/> <!-- 方法名正则匹配拦截配置 -->
<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"
scope="prototype">
<property name="patterns">
<list>
<value>com.lw.coodydruid.mapper.*</value>
</list>
</property>
</bean> <aop:config proxy-target-class="true">
<aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut"/>
</aop:config> </beans>
8.在springboot启动类上,引入配置druid-bean.xml
@ImportResource(locations = { "classpath:druid-bean.xml" })
9.controller类
package com.lw.coodydruid.controller; import com.lw.coodydruid.entity.User;
import com.lw.coodydruid.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController
@RequestMapping("/user")
public class UserController { @Autowired
private UserMapper userMapper; @GetMapping(value = "/get")
public User get() {
return userMapper.getById(1);
} @GetMapping(value = "/list")
public List<User> list() {
return userMapper.getList();
} }
10.Mapper和mapper xml
package com.lw.coodydruid.mapper; import com.lw.coodydruid.entity.User;
import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper
public interface UserMapper { public List<User> getList(); public User getById(int id); }
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lw.coodydruid.mapper.UserMapper"> <resultMap type="com.lw.coodydruid.entity.User" id="userMap">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="sex" property="sex"/>
<result column="age" property="age"/>
<result column="address" property="address"/>
<result column="date_created" property="dateCreated"/>
</resultMap> <select id="getList" resultMap="userMap">
select * from user
</select> <select id="getById" parameterType="java.lang.Integer" resultMap="userMap">
select * from user where id=#{id}
</select> </mapper>
11.测试
- 1.启动springboot启动类,在浏览器上输入http://localhost:8080/druid/index.html,进入Druid登录页面
输入用户名和密码,点击Sign in登录
- 2.访问controller中的方法,http://localhost:8080/user/get
- 3.Druid监控页面---SQL监控
- 4.Druid监控页面---spring监控
SpringBoot之使用Druid连接池,SQL监控和spring监控的更多相关文章
- (二十二)SpringBoot之使用Druid连接池以及SQL监控和spring监控
一.引入maven依赖 <dependencies> <dependency> <groupId>org.springframework.boot</grou ...
- SpringBoot之使用Druid连接池以及SQL监控和spring监控
一.引入maven依赖 <dependencies> <dependency> <groupId>org.springframework.boot</grou ...
- 使用MyBatis集成阿里巴巴druid连接池(不使用spring)
在工作中发现mybatis默认的连接池POOLED,运行时间长了会报莫名其妙的连接失败错误.因此采用阿里巴巴的Druid数据源(码云链接 ,中文文档链接). mybatis更多数据源参考博客链接 . ...
- SpringBoot 配置阿里巴巴Druid连接池
在Spring Boot下默认提供了若干种可用的连接池(dbcp,dbcp2, tomcat, hikari),当然并不支持Druid,Druid来自于阿里系的一个开源连接池,它提供了非常优秀的监控功 ...
- SSM项目下Druid连接池的配置及数据源监控的使用
一,连接池的配置 在pom.xml中添加,druid的maven信息 <dependency> <groupId>com.alibaba</groupId> < ...
- SpringBoot配置MySql数据库和Druid连接池
1.pom文件增加相关依赖 <dependency> <groupId>mysql</groupId> <artifactId>mysql-connec ...
- springboot项目整合druid数据库连接池
Druid连接池是阿里巴巴开源的数据库连接池项目,后来贡献给Apache开源: Druid的作用是负责分配.管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个: D ...
- springboot整合druid连接池、mybatis实现多数据源动态切换
demo环境: JDK 1.8 ,Spring boot 1.5.14 一 整合durid 1.添加druid连接池maven依赖 <dependency> <groupId> ...
- 六:SpringBoot-集成Druid连接池,配置监控界面
SpringBoot-集成Druid连接池,配置监控界面 1.Druid连接池 1.1 Druid特点 2.SpringBoot整合Druid 2.1 引入核心依赖 2.2 数据源配置文件 2.3 核 ...
随机推荐
- windows 10 如何设定计划任务自动执行 python 脚本?
我用 python 写了一些脚本,有一些是爬虫脚本,比如爬取知乎特定话题的热门问题,有一些是定期的统计分析脚本,输出统计结果到文档中.之前我都是手动执行这些脚本,现在我希望如何这些脚本能自动定时执行. ...
- Spring AOP 创建Advice 定义pointcut、advisor
前面定义的advice都是直接植入到代理接口的执行之前和之后,或者在异常发生时,事实上,还可以对植入的时机定义的更细. Pointcut定义了advice的应用时机,在Spring中pointcutA ...
- Outlook 邮件助手
Outlook 邮件助手 1 Overview 2 C# 编程 3 Outlook 设置 3.1 Outlook 2013 3.2 Outlook 2010 1 Overview 本章将示例如何开发一 ...
- flask 与 SQLAlchemy的使用
flask 与 SQLAlchemy的使用 安装模块 pip install flask-sqlalchemy 在单个python中与flask使用 # 文件名:manage.py from flas ...
- ABAP-表修改日志存储
1.设置了变更文档的,可以通过查看标准表CDHDR,CDPOS SE38 -- RSUSR200 ST03N -- 专家模式 2.SE16N维护的数据,可以查看表SE16N_CD_KEY,S ...
- restfulframework引用多对多外键
记录一下工作中遇到的问题 最近在写restfulframework,感觉还是很便利的 首先贴一下文档地址 https://www.django-rest-framework.org/api-guide ...
- 【书评:Oracle查询优化改写】第14章 结尾章
[书评:Oracle查询优化改写]第14章 结尾章 一.1 相关参考文章链接 前13章的链接参考相关连接: [书评:Oracle查询优化改写]第一章 http://blog.itpub.net/26 ...
- MySQL Backup--Xtrabackup介绍
Xtrabackup介绍 Xtrabackup是由Percona公司研发的开源热备工具,支持MYSQL 5.0 以上版本. 由于Xtrabackup支持备份innodb表,实际生产环境中我们使用的工具 ...
- linux中的【;】【&&】【&】【|】【||】说明与用法
原文 “;”分号用法 方式:command1 ; command2 用;号隔开每个命令, 每个命令按照从左到右的顺序,顺序执行, 彼此之间不关心是否失败, 所有命令都会执行. “| ”管道符用法 上一 ...
- windows动态库和静态库VS导入
1. 静态库和动态库 1.1 静态库(.lib) 函数和数据被编译进一个二进制文件(通常扩展名为.LIB).在使用静态库的情况下,在编译链接可执行文件时,链接器从库中复制这些函数和数据并把它们和应用程 ...