博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot集成阿里巴巴Druid监控
阅读量:4709 次
发布时间:2019-06-10

本文共 12310 字,大约阅读时间需要 41 分钟。

druid是阿里巴巴开源的数据库连接池,提供了优秀的对数据库操作的监控功能,本文要讲解一下springboot项目怎么集成druid。

本文在基于jpa的项目下开发,首先在pom文件中额外加入druid依赖,pom文件如下:

4.0.0
com.dalaoyang
springboot_druid
0.0.1-SNAPSHOT
jar
springboot_druid
springboot_druid
org.springframework.boot
spring-boot-starter-parent
1.5.12.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-data-jpa
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-devtools
runtime
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-test
test
com.alibaba
druid
1.0.28
org.springframework.boot
spring-boot-maven-plugin

application.properties上半段和整合jpa一点没变,下面加入了一些druid的配置,如果对druid的配置有什么不理解的,可以去网上查一下。(这篇文章我觉得写的很好,)

#端口号server.port=8888##validate  加载hibernate时,验证创建数据库表结构##create   每次加载hibernate,重新创建数据库表结构,这就是导致数据库表数据丢失的原因。##create-drop        加载hibernate时创建,退出是删除表结构##update                 加载hibernate自动更新数据库结构##validate 启动时验证表的结构,不会创建表##none  启动时不做任何操作spring.jpa.hibernate.ddl-auto=create##控制台打印sqlspring.jpa.show-sql=true##数据库配置##数据库地址spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false##数据库用户名spring.datasource.username=root##数据库密码spring.datasource.password=root##数据库驱动spring.datasource.driver-class-name=com.mysql.jdbc.Driver#这里是不同的#使用druid的话 需要多配置一个属性spring.datasource.typespring.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  spring.datasource.validationQuery=SELECT 1 FROM DUAL  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记录

然后在项目中加入DruidConfig,简单讲解一下,这个配置文件主要是加载application.properties的配置,代码如下:

package com.dalaoyang.config;import java.sql.SQLException;import javax.sql.DataSource;import org.apache.log4j.Logger;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 com.alibaba.druid.pool.DruidDataSource;/** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.config * @email yangyang@dalaoyang.cn * @date 2018/4/12 */@Configurationpublic class DruidConfig {    private Logger logger = Logger.getLogger(this.getClass());    @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    @Primary  //主数据源    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);        try {            datasource.setFilters(filters);        } catch (SQLException e) {            logger.error("druid configuration Exception", e);        }        datasource.setConnectionProperties(connectionProperties);        return datasource;    }}

然后创建DruidFilter,代码如下:

package com.dalaoyang.filter;import javax.servlet.annotation.WebFilter;import javax.servlet.annotation.WebInitParam;import com.alibaba.druid.support.http.WebStatFilter;/** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.filter * @email yangyang@dalaoyang.cn * @date 2018/4/12 */@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",        initParams={                @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//忽略资源        })public class DruidFilter extends WebStatFilter  {}

新建DruidServlet,在类上面加注解@WebServlet,其中配置了登录druid监控页面的账号密码,白名单黑名单之类的配置,代码如下:

package com.dalaoyang.servlet;import javax.servlet.annotation.WebInitParam;import javax.servlet.annotation.WebServlet;import com.alibaba.druid.support.http.StatViewServlet;/** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.servlet * @email yangyang@dalaoyang.cn * @date 2018/4/12 */@WebServlet(urlPatterns="/druid/*",        initParams={                @WebInitParam(name="allow",value=""),// IP白名单(没有配置或者为空,则允许所有访问)                @WebInitParam(name="deny",value=""),// IP黑名单 (deny优先于allow)                @WebInitParam(name="loginUsername",value="admin"),// 登录druid管理页面用户名                @WebInitParam(name="loginPassword",value="admin")// 登录druid管理页面密码        })public class DruidServlet extends StatViewServlet {}

然后在启动类加入注解@ServletComponentScan,让项目扫描到servlet,代码如下:

package com.dalaoyang;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.ServletComponentScan;@SpringBootApplication// 启动类必须加入@ServletComponentScan注解,否则无法扫描到servlet@ServletComponentScanpublic class SpringbootDruidApplication {    public static void main(String[] args) {        SpringApplication.run(SpringbootDruidApplication.class, args);    }}

剩余的就是和整合jpa一样的entity(实体类),repository(数据操作层),controller(测试使用的controller),直接展示代码。

City

package com.dalaoyang.entity;import javax.persistence.*;/** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.Entity * @email 397600342@qq.com * @date 2018/4/7 */@Entity@Table(name="city")public class City {    @Id    @GeneratedValue(strategy=GenerationType.AUTO)    private int cityId;    private String cityName;    private String cityIntroduce;    public City(int cityId, String cityName, String cityIntroduce) {        this.cityId = cityId;        this.cityName = cityName;        this.cityIntroduce = cityIntroduce;    }    public City(String cityName, String cityIntroduce) {        this.cityName = cityName;        this.cityIntroduce = cityIntroduce;    }    public City() {    }    public int getCityId() {        return cityId;    }    public void setCityId(int cityId) {        this.cityId = cityId;    }    public String getCityName() {        return cityName;    }    public void setCityName(String cityName) {        this.cityName = cityName;    }    public String getCityIntroduce() {        return cityIntroduce;    }    public void setCityIntroduce(String cityIntroduce) {        this.cityIntroduce = cityIntroduce;    }}

CityRepository

package com.dalaoyang.repository;import com.dalaoyang.entity.City;import org.springframework.data.jpa.repository.JpaRepository;/** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.Repository * @email 397600342@qq.com * @date 2018/4/7 */public interface CityRepository extends JpaRepository
{}

CityController

package com.dalaoyang.controller;import com.dalaoyang.entity.City;import com.dalaoyang.repository.CityRepository;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;/** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.controller * @email 397600342@qq.com * @date 2018/4/7 */@RestControllerpublic class CityController {    @Autowired    private CityRepository cityRepository;    //http://localhost:8888/saveCity?cityName=北京&cityIntroduce=中国首都    @GetMapping(value = "saveCity")    public String saveCity(String cityName,String cityIntroduce){        City city = new City(cityName,cityIntroduce);        cityRepository.save(city);        return "success";    }    //http://localhost:8888/deleteCity?cityId=2    @GetMapping(value = "deleteCity")    public String deleteCity(int cityId){        cityRepository.delete(cityId);        return "success";    }    //http://localhost:8888/updateCity?cityId=3&cityName=沈阳&cityIntroduce=辽宁省省会    @GetMapping(value = "updateCity")    public String updateCity(int cityId,String cityName,String cityIntroduce){        City city = new City(cityId,cityName,cityIntroduce);        cityRepository.save(city);        return "success";    }    //http://localhost:8888/getCityById?cityId=3    @GetMapping(value = "getCityById")    public City getCityById(int cityId){        City city = cityRepository.findOne(cityId);        return city;    }}

然后启动项目,可以看到控制台已经创建了city表。

162b860bd2e756f6?w=2410&h=888&f=jpeg&s=765639

然后访问http://localhost:8888/druid,可以看到如下图:

162b8613c60b3565?w=1608&h=734&f=jpeg&s=78934

输入账号密码admin,admin,如下图

162b861b46aa9d53?w=2188&h=1170&f=jpeg&s=269293

然后这时我们可以访问http://localhost:8888/saveCity?cityName=北京&cityIntroduce=中国首都

然后点击导航上面的SQL监控,如下图,

162b862f0ed63d6b?w=2526&h=800&f=jpeg&s=242023

从上图可以看到启动项目创建表的sql已经刚刚执行的sql。到这里整合已经完成了。

源码下载 :

个人网站:

转载于:https://www.cnblogs.com/dalaoyang/p/8807511.html

你可能感兴趣的文章
使用Siege进行WEB压力测试
查看>>
斑马为什么有条纹?
查看>>
android多层树形结构列表学习笔记
查看>>
Android_去掉EditText控件周围橙色高亮区域
查看>>
《构建之法》第一、二、十六章阅读笔记
查看>>
Git Stash用法
查看>>
sql server 2008学习8 sql server存储和索引结构
查看>>
Jquery radio选中
查看>>
memcached 细究(三)
查看>>
IT常用单词
查看>>
拓扑排序
查看>>
NYOJ--32--SEARCH--组合数
查看>>
gulpfile 压缩模板
查看>>
【34.14%】【BZOJ 3110】 [Zjoi2013]K大数查询
查看>>
【 henuacm2016级暑期训练-动态规划专题 A 】Cards
查看>>
第五篇:白话tornado源码之褪去模板的外衣
查看>>
设备常用框架framework
查看>>
bootstrap模态框和select2合用时input无法获取焦点(转)
查看>>
MockObject
查看>>
BZOJ4516: [Sdoi2016]生成魔咒(后缀自动机)
查看>>