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:
- <?xml version="1.0" encoding="UTF-8"?>
- <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/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.dalaoyang</groupId>
- <artifactId>springboot_druid</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- <name>springboot_druid</name>
- <description>springboot_druid</description>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>1.5.12.RELEASE</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <java.version>1.8</java.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jpa</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-devtools</artifactId>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.0.28</version>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
- </project>
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)
- #The port number
- server.port=8888
- ##validate When loading hibernate, verify the database table structure created
- ##create Every time hibernate is loaded, the database table structure is recreated, which is the reason for the loss of database table data.
- ##create-drop is created when hibernate is loaded, and the exit is to delete the table structure
- ##update Load hibernate to automatically update the database structure
- ##validate Validate the structure of the table at startup, the table will not be created
- ##none do nothing at startup
- spring.jpa.hibernate.ddl-auto=create
- ##Console print sql
- spring.jpa.show-sql=true
- ##Database configuration
- ##Database address
- spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
- ##database username
- spring.datasource.username=root
- ##Database password
- spring.datasource.password=root
- ##Database driver
- spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- Jiangsu Surrogacy
- Jiangsu Surrogacy Company
- #here is different
- #If you use druid, you need to configure one more property spring.datasource.type
- spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
- # Configuration information of the connection pool
- # Initialize size, min, max
- spring.datasource.initialSize=5
- spring.datasource.minIdle=5
- spring.datasource.maxActive=20
- # Configure the time to wait for a timeout to get a connection
- spring.datasource.maxWait=60000
- # Configure how long the interval is to perform detection and detect idle connections that need to be closed, in milliseconds
- spring.datasource.timeBetweenEvictionRunsMillis = 60000
- # Configure the minimum lifetime of a connection in the pool, in milliseconds
- spring.datasource.minEvictableIdleTimeMillis = 300000
- spring.datasource.validationQuery=SELECT 1 FROM DUAL
- spring.datasource.testWhileIdle=true
- spring.datasource.testOnBorrow=false
- spring.datasource.testOnReturn=false
- # Open PSCache and specify the size of PSCache on each connection
- spring.datasource.poolPreparedStatements=true
- spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
- # Configure the filters for monitoring statistics interception. After removing, the monitoring interface sql cannot be counted. 'wall' is used for firewalls
- spring.datasource.filters=stat,wall,log4j
- # Turn on the mergeSql function through the connectProperties property; slow SQL records
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:
- 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 [email protected]
- * @date 2018/4/12
- */
- @Configuration
- public 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 //Primary data source
- 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;
- }
- }
Then create DruidFilter, the code is as follows:
- 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 [email protected]
- * @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 {
- }
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:
- 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 [email protected]
- * @date 2018/4/12
- */
- @WebServlet(urlPatterns="/druid/*",
- initParams={
- @WebInitParam(name="allow",value=""),// IP whitelist (no configuration or empty, all access is allowed)
- @WebInitParam(name="deny",value=""),// IP blacklist (deny takes precedence over allow)
- @WebInitParam(name="loginUsername",value="admin"),// Login user name of druid management page
- @WebInitParam(name="loginPassword",value="admin")// Login druid management page password
- })
- public class DruidServlet extends StatViewServlet {
- }
Then add the annotation @ServletComponentScan to the startup class to scan the project to the servlet. The code is as follows:
- package com.dalaoyang;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.boot.web.servlet.ServletComponentScan;
- @SpringBootApplication
- // The startup class must be annotated with @ServletComponentScan, otherwise the servlet cannot be scanned
- @ServletComponentScan
- public class SpringbootDruidApplication {
- public static void main(String[] args) {
- SpringApplication.run(SpringbootDruidApplication.class, args);
- }
- }
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
- package com.dalaoyang.entity;
- import javax.persistence.*;
- /**
- * @author dalaoyang
- * @Description
- * @project springboot_learn
- * @package com.dalaoyang.Entity
- * @email [email protected]
- * @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 [email protected]
- * @date 2018/4/7
- */
- public interface CityRepository extends JpaRepository<City,Integer> {
- }
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 [email protected]
- * @date 2018/4/7
-
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/ -
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 - */
- @RestController
- public class CityController {
- @Autowired
- private CityRepository cityRepository;
- //http://localhost:8888/saveCity?cityName=Beijing&cityIntroduce=China Capital
- @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=Shenyang&cityIntroduce=Capital of Liaoning Province
- @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;
- }
- }
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.