druid is an open source database connection pool from Alibaba, which provides excellent monitoring functions for database operations. This article will explain how to integrate druid into springboot project.
This article is developed under a JPA-based project. First, additional druid dependencies are added 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> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>
The first half of application.properties and the integrated jpa have not changed at all. Some druid configurations have been added below. If you don’t understand the configuration of druid, you can check it online. (I think this article is well written, Portal)
#Port number server.port=8888##validate When hibernate is loaded, verify the creation of database table structure##create Each time hibernate is loaded, recreate the database table structure, which is the reason for the loss of database table data. ##create-drop Created when hibernate is loaded, exit is to delete the table structure ##update Loading hibernate automatically updates the database structure ##validate Verify the structure of the table when starting, and will not create table ##none Do not do anything when starting spring.jpa.hibernate.ddl-auto=create##Console prints sqlspring.jpa.show-sql=true##Database configuration##Database address spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false##Database username spring.datasource.usernam e=root##Database password spring.datasource.password=root##Database driver spring.datasource.driver-class-name=com.mysql.jdbc.Driver# Here are different#If you use druid, you need to configure one more property spring.datasource.typespring.datasource.type=com.alibaba.druid.pool.DruidDataSource #Configuration information of the connection pool# Initialize size, minimum, maximum spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 # Configure the time to get the connection waiting timeout spring.datasource.maxWait=60000 # Configure how long it takes to perform a detection interval to detect idle connections that need to be closed, unit is milliseconds spring.datasource.timeBetweenEvictionRunsMillis=60000 # Configure the minimum time for a connection to survive in the pool, unit is 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 filters for monitoring statistics intercepting. After removing it, the monitoring interface SQL cannot be counted. 'wall' is used for firewall spring.datasource.filters=stat,wall,log4j# Use the connectProperties property to open mergeSql function; slow SQL records
Then add DruidConfig to the project and briefly explain that this configuration file mainly loads the configuration of application.properties, and 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 */@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 //Main 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 a 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/*")//Ignore resources})public class DruidFilter extends WebStatFilter {}
Create a new DruidServlet, add annotation to the class @WebServlet, which configures the account password for login to the druid monitoring page, whitelist and blacklist configurations, 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"),// Log in to the druid management page username@WebInitParam(name="loginPassword",value="admin")// Log in to the druid management page password}) public class DruidServlet extends StatViewServlet {}
Then add the annotation @ServletComponentScan to the startup class and let the project scan 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 include the @ServletComponentScan annotation, otherwise it cannot be scanned to servlet@ServletComponentScan public class SpringbootDruidApplication { public static void main(String[] args) { SpringApplication.run(SpringbootDruidApplication.class, args); }}The rest are the same entity (entity class), repository (data operation layer), controller (controller used for testing) as integrated jpa, which directly displays the code.
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 */@RestControllerpublic class CityController { @Autowired private CityRepository cityRepository; //http://localhost:8888/saveCity?cityName=Beijing&cityIntroduce=China's 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=Liaoning Provincial Capital @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 and you can see that the console has created the city table.
Then visit http://localhost:8888/druid and you can see the following figure:
Enter the account password admin, admin, as shown in the following figure
Then at this time we can visit http://localhost:8888/saveCity?cityName=Beijing&cityIntroduce=China's capital
Then click on the SQL monitoring above, as shown in the figure below.
From the above figure, you can see that the SQL that started the project creation table has just been executed. The integration has been completed here.
Source code download: https://gitee.com/dalaoyang/springboot_learn
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.