Example code for SpringBoot to integrate Alibaba Druid monitoring

Druid is Alibaba's open source database connection pool, which provides excellent monitoring functions for database operations. This article will explain how the springboot project integrates Druid.

This article is developed under a jpa-based project. First, add druid dependencies to the pom file. The pom file is as follows:

  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>
copy code

The first half of application.properties and the integration of jpa have not changed at all. Some druid configurations are added below. If you don't understand the druid configuration, you can check it online. (I think this article is well written, Portal)

  1. #The port number
  2. server.port=8888
  3. ##validate When loading hibernate, verify the database table structure created
  4. ##create Every time hibernate is loaded, the database table structure is recreated, which is the reason for the loss of database table data.
  5. ##create-drop is created when hibernate is loaded, and the exit is to delete the table structure
  6. ##update Load hibernate to automatically update the database structure
  7. ##validate Validate the structure of the table at startup, the table will not be created
  8. ##none do nothing at startup
  9. spring.jpa.hibernate.ddl-auto=create
  10. ##Console print sql
  11. spring.jpa.show-sql=true
  12. ##Database configuration
  13. ##Database address
  14. spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
  15. ##database username
  16. spring.datasource.username=root
  17. ##Database password
  18. spring.datasource.password=root
  19. ##Database driver
  20. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  21. Jiangsu Surrogacy
  22. Jiangsu Surrogacy Company
  23. #here is different
  24. #If you use druid, you need to configure one more property spring.datasource.type
  25. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  26. # Configuration information of the connection pool
  27. # Initialize size, min, max
  28. spring.datasource.initialSize=5
  29. spring.datasource.minIdle=5
  30. spring.datasource.maxActive=20
  31. # Configure the time to wait for a timeout to get a connection
  32. spring.datasource.maxWait=60000
  33. # Configure how long the interval is to perform detection and detect idle connections that need to be closed, in milliseconds
  34. spring.datasource.timeBetweenEvictionRunsMillis = 60000
  35. # Configure the minimum lifetime of a connection in the pool, in milliseconds
  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. # Open PSCache and specify the size of PSCache on each connection
  42. spring.datasource.poolPreparedStatements=true
  43. spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
  44. # Configure the filters for monitoring statistics interception. After removing, the monitoring interface sql cannot be counted. 'wall' is used for firewalls
  45. spring.datasource.filters=stat,wall,log4j
  46. # Turn on the mergeSql function through the connectProperties property; slow SQL records
copy code

Then add DruidConfig to the project, briefly explain, this configuration file is mainly to load the configuration of application.properties, the code is as follows:

  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 //Primary data source
  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. }
copy code

Then create DruidFilter, the code is as follows:

  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. }
copy code

Create a new DruidServlet and add the annotation @WebServlet to the class, which configures the account password for logging in to the Druid monitoring page, the configuration such as the whitelist and blacklist, and the code is as follows:

  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 whitelist (no configuration or empty, all access is allowed)
  16. @WebInitParam(name="deny",value=""),// IP blacklist (deny takes precedence over allow)
  17. @WebInitParam(name="loginUsername",value="admin"),// Login user name of druid management page
  18. @WebInitParam(name="loginPassword",value="admin")// Login druid management page password
  19. })
  20. public class DruidServlet extends StatViewServlet {
  21. }
copy code

Then add the annotation @ServletComponentScan to the startup class to scan the project to the servlet. The code is as follows:

  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. // The startup class must be annotated with @ServletComponentScan, otherwise the servlet cannot be scanned
  7. @ServletComponentScan
  8. public class SpringbootDruidApplication {
  9. public static void main(String[] args) {
  10. SpringApplication.run(SpringbootDruidApplication.class, args);
  11. }
  12. }
copy code

The rest is the same entity (entity class), repository (data operation layer), controller (controller used for testing) as the integrated jpa, and the code is displayed directly.

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. }
copy code

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. }
copy code

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=Beijing&cityIntroduce=China Capital
  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=Shenyang&cityIntroduce=Capital of Liaoning Province
  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. }
copy code

Then start the project, you can see that the console has created the city table.

Then visit http://localhost:8888/druid, you can see the following picture:

Enter the account password admin, admin, as shown below

Then we can visit http://localhost:8888/saveCity?cityName=Beijing&cityIntroduce=China Capital

Then click on the SQL monitoring above the navigation, as shown below,

From the above figure, you can see that the sql that started the project to create the table has just executed the sql. The integration has been completed here.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325235612&siteId=291194637