SpringBoot集成阿里巴巴Druid监控的示例代码

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

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

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.dalaoyang</groupId>
  6. <artifactId>springboot_druid</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <packaging>jar</packaging>
  9. <name>springboot_druid</name>
  10. <description>springboot_druid</description>
  11. <parent>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-parent</artifactId>
  14. <version>1.5.12.RELEASE</version>
  15. <relativePath/> <!-- lookup parent from repository -->
  16. </parent>
  17. <properties>
  18. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  19. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  20. <java.version>1.8</java.version>
  21. </properties>
  22. <dependencies>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-data-jpa</artifactId>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.springframework.boot</groupId>
  29. <artifactId>spring-boot-starter-web</artifactId>
  30. </dependency>
  31. <dependency>
  32. <groupId>org.springframework.boot</groupId>
  33. <artifactId>spring-boot-devtools</artifactId>
  34. <scope>runtime</scope>
  35. </dependency>
  36. <dependency>
  37. <groupId>mysql</groupId>
  38. <artifactId>mysql-connector-java</artifactId>
  39. <scope>runtime</scope>
  40. </dependency>
  41. <dependency>
  42. <groupId>org.springframework.boot</groupId>
  43. <artifactId>spring-boot-starter-test</artifactId>
  44. <scope>test</scope>
  45. </dependency>
  46. <dependency>
  47. <groupId>com.alibaba</groupId>
  48. <artifactId>druid</artifactId>
  49. <version>1.0.28</version>
  50. </dependency>
  51. </dependencies>
  52. <build>
  53. <plugins>
  54. <plugin>
  55. <groupId>org.springframework.boot</groupId>
  56. <artifactId>spring-boot-maven-plugin</artifactId>
  57. </plugin>
  58. </plugins>
  59. </build>
  60. </project>
复制代码

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

  1. #端口号
  2. server.port=8888
  3. ##validate 加载hibernate时,验证创建数据库表结构
  4. ##create 每次加载hibernate,重新创建数据库表结构,这就是导致数据库表数据丢失的原因。
  5. ##create-drop 加载hibernate时创建,退出是删除表结构
  6. ##update 加载hibernate自动更新数据库结构
  7. ##validate 启动时验证表的结构,不会创建表
  8. ##none 启动时不做任何操作
  9. spring.jpa.hibernate.ddl-auto=create
  10. ##控制台打印sql
  11. spring.jpa.show-sql=true
  12. ##数据库配置
  13. ##数据库地址
  14. spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
  15. ##数据库用户名
  16. spring.datasource.username=root
  17. ##数据库密码
  18. spring.datasource.password=root
  19. ##数据库驱动
  20. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  21. 江苏代孕
  22. 江苏代孕公司
  23. #这里是不同的
  24. #使用druid的话 需要多配置一个属性spring.datasource.type
  25. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  26. # 连接池的配置信息
  27. # 初始化大小,最小,最大
  28. spring.datasource.initialSize=5
  29. spring.datasource.minIdle=5
  30. spring.datasource.maxActive=20
  31. # 配置获取连接等待超时的时间
  32. spring.datasource.maxWait=60000
  33. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  34. spring.datasource.timeBetweenEvictionRunsMillis=60000
  35. # 配置一个连接在池中最小生存的时间,单位是毫秒
  36. spring.datasource.minEvictableIdleTimeMillis=300000
  37. spring.datasource.validationQuery=SELECT 1 FROM DUAL
  38. spring.datasource.testWhileIdle=true
  39. spring.datasource.testOnBorrow=false
  40. spring.datasource.testOnReturn=false
  41. # 打开PSCache,并且指定每个连接上PSCache的大小
  42. spring.datasource.poolPreparedStatements=true
  43. spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
  44. # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
  45. spring.datasource.filters=stat,wall,log4j
  46. # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
复制代码

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

  1. package com.dalaoyang.config;
  2. import java.sql.SQLException;
  3. import javax.sql.DataSource;
  4. import org.apache.log4j.Logger;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.context.annotation.Primary;
  9. import com.alibaba.druid.pool.DruidDataSource;
  10. /**
  11. * @author dalaoyang
  12. * @Description
  13. * @project springboot_learn
  14. * @package com.dalaoyang.config
  15. * @email [email protected]
  16. * @date 2018/4/12
  17. */
  18. @Configuration
  19. public class DruidConfig {
  20. private Logger logger = Logger.getLogger(this.getClass());
  21. @Value("${spring.datasource.url}")
  22. private String dbUrl;
  23. @Value("${spring.datasource.username}")
  24. private String username;
  25. @Value("${spring.datasource.password}")
  26. private String password;
  27. @Value("${spring.datasource.driver-class-name}")
  28. private String driverClassName;
  29. @Value("${spring.datasource.initialSize}")
  30. private int initialSize;
  31. @Value("${spring.datasource.minIdle}")
  32. private int minIdle;
  33. @Value("${spring.datasource.maxActive}")
  34. private int maxActive;
  35. @Value("${spring.datasource.maxWait}")
  36. private int maxWait;
  37. @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
  38. private int timeBetweenEvictionRunsMillis;
  39. @Value("${spring.datasource.minEvictableIdleTimeMillis}")
  40. private int minEvictableIdleTimeMillis;
  41. @Value("${spring.datasource.validationQuery}")
  42. private String validationQuery;
  43. @Value("${spring.datasource.testWhileIdle}")
  44. private boolean testWhileIdle;
  45. @Value("${spring.datasource.testOnBorrow}")
  46. private boolean testOnBorrow;
  47. @Value("${spring.datasource.testOnReturn}")
  48. private boolean testOnReturn;
  49. @Value("${spring.datasource.poolPreparedStatements}")
  50. private boolean poolPreparedStatements;
  51. @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
  52. private int maxPoolPreparedStatementPerConnectionSize;
  53. @Value("${spring.datasource.filters}")
  54. private String filters;
  55. @Value("{spring.datasource.connectionProperties}")
  56. private String connectionProperties;
  57. @Bean
  58. @Primary //主数据源
  59. public DataSource dataSource(){
  60. DruidDataSource datasource = new DruidDataSource();
  61. datasource.setUrl(this.dbUrl);
  62. datasource.setUsername(username);
  63. datasource.setPassword(password);
  64. datasource.setDriverClassName(driverClassName);
  65. //configuration
  66. datasource.setInitialSize(initialSize);
  67. datasource.setMinIdle(minIdle);
  68. datasource.setMaxActive(maxActive);
  69. datasource.setMaxWait(maxWait);
  70. datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  71. datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  72. datasource.setValidationQuery(validationQuery);
  73. datasource.setTestWhileIdle(testWhileIdle);
  74. datasource.setTestOnBorrow(testOnBorrow);
  75. datasource.setTestOnReturn(testOnReturn);
  76. datasource.setPoolPreparedStatements(poolPreparedStatements);
  77. datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
  78. try {
  79. datasource.setFilters(filters);
  80. } catch (SQLException e) {
  81. logger.error("druid configuration Exception", e);
  82. }
  83. datasource.setConnectionProperties(connectionProperties);
  84. return datasource;
  85. }
  86. }
复制代码

然后创建DruidFilter,代码如下:

  1. package com.dalaoyang.filter;
  2. import javax.servlet.annotation.WebFilter;
  3. import javax.servlet.annotation.WebInitParam;
  4. import com.alibaba.druid.support.http.WebStatFilter;
  5. /**
  6. * @author dalaoyang
  7. * @Description
  8. * @project springboot_learn
  9. * @package com.dalaoyang.filter
  10. * @email [email protected]
  11. * @date 2018/4/12
  12. */
  13. @WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
  14. initParams={
  15. @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//忽略资源
  16. }
  17. )
  18. public class DruidFilter extends WebStatFilter {
  19. }
复制代码

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

  1. package com.dalaoyang.servlet;
  2. import javax.servlet.annotation.WebInitParam;
  3. import javax.servlet.annotation.WebServlet;
  4. import com.alibaba.druid.support.http.StatViewServlet;
  5. /**
  6. * @author dalaoyang
  7. * @Description
  8. * @project springboot_learn
  9. * @package com.dalaoyang.servlet
  10. * @email [email protected]
  11. * @date 2018/4/12
  12. */
  13. @WebServlet(urlPatterns="/druid/*",
  14. initParams={
  15. @WebInitParam(name="allow",value=""),// IP白名单(没有配置或者为空,则允许所有访问)
  16. @WebInitParam(name="deny",value=""),// IP黑名单 (deny优先于allow)
  17. @WebInitParam(name="loginUsername",value="admin"),// 登录druid管理页面用户名
  18. @WebInitParam(name="loginPassword",value="admin")// 登录druid管理页面密码
  19. })
  20. public class DruidServlet extends StatViewServlet {
  21. }
复制代码

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

  1. package com.dalaoyang;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.boot.web.servlet.ServletComponentScan;
  5. @SpringBootApplication
  6. // 启动类必须加入@ServletComponentScan注解,否则无法扫描到servlet
  7. @ServletComponentScan
  8. public class SpringbootDruidApplication {
  9. public static void main(String[] args) {
  10. SpringApplication.run(SpringbootDruidApplication.class, args);
  11. }
  12. }
复制代码

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

City

  1. package com.dalaoyang.entity;
  2. import javax.persistence.*;
  3. /**
  4. * @author dalaoyang
  5. * @Description
  6. * @project springboot_learn
  7. * @package com.dalaoyang.Entity
  8. * @email [email protected]
  9. * @date 2018/4/7
  10. */
  11. @Entity
  12. @Table(name="city")
  13. public class City {
  14. @Id
  15. @GeneratedValue(strategy=GenerationType.AUTO)
  16. private int cityId;
  17. private String cityName;
  18. private String cityIntroduce;
  19. public City(int cityId, String cityName, String cityIntroduce) {
  20. this.cityId = cityId;
  21. this.cityName = cityName;
  22. this.cityIntroduce = cityIntroduce;
  23. }
  24. public City(String cityName, String cityIntroduce) {
  25. this.cityName = cityName;
  26. this.cityIntroduce = cityIntroduce;
  27. }
  28. public City() {
  29. }
  30. public int getCityId() {
  31. return cityId;
  32. }
  33. public void setCityId(int cityId) {
  34. this.cityId = cityId;
  35. }
  36. public String getCityName() {
  37. return cityName;
  38. }
  39. public void setCityName(String cityName) {
  40. this.cityName = cityName;
  41. }
  42. public String getCityIntroduce() {
  43. return cityIntroduce;
  44. }
  45. public void setCityIntroduce(String cityIntroduce) {
  46. this.cityIntroduce = cityIntroduce;
  47. }
  48. }
复制代码

CityRepository

  1. package com.dalaoyang.repository;
  2. import com.dalaoyang.entity.City;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. /**
  5. * @author dalaoyang
  6. * @Description
  7. * @project springboot_learn
  8. * @package com.dalaoyang.Repository
  9. * @email [email protected]
  10. * @date 2018/4/7
  11. */
  12. public interface CityRepository extends JpaRepository<City,Integer> {
  13. }
复制代码

CityController

  1. package com.dalaoyang.controller;
  2. import com.dalaoyang.entity.City;
  3. import com.dalaoyang.repository.CityRepository;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. /**
  8. * @author dalaoyang
  9. * @Description
  10. * @project springboot_learn
  11. * @package com.dalaoyang.controller
  12. * @email [email protected]
  13. * @date 2018/4/7

  14. http://www.ljhseo.com/
    http://www.xyrjkf.net/
    http://www.xyrjkf.cn/
    http://www.xyrjkf.com.cn/
    http://www.zjdygsi.cn/ 
    http://www.zjdaiyun.cn/ 
    http://www.jsdygsi.cn/ 
    http://www.xyrjkf.top/ 
    http://www.xyrjkf.com/
    http://www.daiyunzj.cn/

  15. http://ljhseo.com

    http://xyrjkf.net
    http://xyrjkf.cn
    http://xyrjkf.com.cn
    http://zjdygsi.cn
    http://zjdaiyun.cn
    http://jsdygsi.cn
    http://xyrjkf.top
    http://xyrjkf.com
    http://daiyunzj.cn

  16. */
  17. @RestController
  18. public class CityController {
  19. @Autowired
  20. private CityRepository cityRepository;
  21. //http://localhost:8888/saveCity?cityName=北京&cityIntroduce=中国首都
  22. @GetMapping(value = "saveCity")
  23. public String saveCity(String cityName,String cityIntroduce){
  24. City city = new City(cityName,cityIntroduce);
  25. cityRepository.save(city);
  26. return "success";
  27. }
  28. //http://localhost:8888/deleteCity?cityId=2
  29. @GetMapping(value = "deleteCity")
  30. public String deleteCity(int cityId){
  31. cityRepository.delete(cityId);
  32. return "success";
  33. }
  34. //http://localhost:8888/updateCity?cityId=3&cityName=沈阳&cityIntroduce=辽宁省省会
  35. @GetMapping(value = "updateCity")
  36. public String updateCity(int cityId,String cityName,String cityIntroduce){
  37. City city = new City(cityId,cityName,cityIntroduce);
  38. cityRepository.save(city);
  39. return "success";
  40. }
  41. //http://localhost:8888/getCityById?cityId=3
  42. @GetMapping(value = "getCityById")
  43. public City getCityById(int cityId){
  44. City city = cityRepository.findOne(cityId);
  45. return city;
  46. }
  47. }
复制代码

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

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

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

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

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

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

猜你喜欢

转载自www.cnblogs.com/ljhseocom/p/8987711.html