OpenWrite version:
Welcome to my GitHub
Github.com/zq2599/blog…
Content: all original article classification summary and supporting source code, involving Java, Docker, Kubernetes, DevOPS, etc.;
This article is “MyBatis primary combat” series of the third, we will combat springboot, MyBatis, DRUid integration, and verification;
About the druid
- Druid is a database connection pool and provides powerful monitoring and extension capabilities.
- Official GitHub address: github.com/alibaba/dru…
- This integration uses the official DurID starter named druid-spring-boot-starter whose version is 1.1.17. The druid version is 1.1.17
This paper gives an overview of
This article consists of the following contents:
- New SpringBoot project with detailed integration with Druid
- Write and execute unit test code and avoid a problem with integration Druid;
- Start the Springboot application and verify that the basic function is normal by Swagger.
- Verify that the Druid connection pool is used by the breakpoint;
- Experience the monitoring page provided by Druid
Download the source code
- If you don’t want to code, you can download all the source code at GitHub, with the address and link information listed in the following table (github.com/zq2599/blog…
The name of the | link | note |
---|---|---|
Project home page | Github.com/zq2599/blog… | The project’s home page on GitHub |
Git repository address (HTTPS) | Github.com/zq2599/blog… | The project source warehouse address, HTTPS protocol |
Git repository address (SSH) | [email protected]:zq2599/blog_demos.git | The project source warehouse address, SSH protocol |
- This Git project has multiple folders. The application of this chapter is in the Mybatis folder, as shown in the red box below:
Springboot + Mybatis + Druid + Swagger
The steps required for the entire integration are listed below to avoid omission:
- Create springBoot project;
- Add mybaits, Druid, swagger dependencies to POM. XML;
- Configure mybatis – config. XML;
- Configure application. Yml, which contains data source, Mybatis, druid;
- Springboot starts the class, specifying MapperScan;
- Swagger configuration class;
- Druid configuration class;
- Database entity class;
- Mybatis mapper configuration file;
- Mapper class of Mybatis;
- Business code;
- Follow-up development can be carried out according to the above list;
The development of
- The database and table structure used in this paper is exactly the same as that in MyBatis Primary Combat: Spring Boot integration.
- MyBatis is a new project named Druidonesource. It is a new project named Druidonesource. It is a new project named Druidonesource.
Add version management for druid to the parent project:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.17</version>
</dependency>
Copy the code
- The pom.xml for the new project Druidonesource reads as follows:
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bolingcavalry</groupId>
<artifactId>mybatis</artifactId>
<version>1.0 the SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<groupId>com.bolingcavalry</groupId>
<artifactId>druidonesource</artifactId>
<version>0.0.1 - the SNAPSHOT</version>
<name>druidonesource</name>
<description>Demo project for Mybatis Druid (one datasource) in Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<! -- swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Copy the code
- New mybatis – config. XML:
<! DOCTYPEconfiguration
PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<! Classes in mapping files do not need to write full path
<package name="com.bolingcavalry.druidonesource.entity"/>
</typeAliases>
</configuration>
Copy the code
- The stat-view-servlet allows you to log in to the druid monitoring page. The stat-view-servlet allows you to log in to the druid monitoring page.
server:
port: 8080
spring:
# 1. JDBC data sources
datasource:
username: root
password: 123456
url: JDBC: mysql: / / 192.168.50.43:3306 / mybatis? useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
#2. Connection pool configuration
druid:
Initialize the number of connections in the pool
initial-size: 5
min-idle: 5
max-active: 20
Set the connection wait timeout
max-wait: 60000
Configure how often to detect idle connections that need to be closed, in milliseconds
time-between-eviction-runs-millis: 60000
Set the minimum time for a connection to live in the pool in milliseconds
min-evictable-idle-time-millis: 30000
Set the maximum number of milliseconds for a connection to live in the pool
max-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM user
test-while-idle: true
test-on-borrow: true
test-on-return: false
PreparedStatement (PSCache) preparedStatement (PSCache) preparedStatement (PSCache
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
# Configure the filters for monitoring statistics interception. After removing the filters, the MONITORING interface SQL cannot be counted. 'wall' is used for the firewall
filters: stat,wall,slf4j
filter:
stat:
merge-sql: true
slow-sql-millis: 5000
#3. Basic monitoring configuration
web-stat-filter:
enabled: true
url-pattern: / *
# set which urls are not counted
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
session-stat-enable: true
session-stat-max-count: 100
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: true
Set the login name and password of the monitoring page
login-username: admin
login-password: admin
allow: 127.0. 01.
# deny: 192.168.1.100
# mybatis configuration
mybatis:
# Config file location
config-location: classpath:mybatis-config.xml
# Map file location
mapper-locations: classpath:mappers/*Mapper.xml
# log configuration
logging:
level:
root: INFO
com:
bolingcavalry:
druidonesource:
mapper: debug
Copy the code
- To create a startup class, use the MapperScan annotation:
package com.bolingcavalry.druidonesource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.bolingcavalry.druidonesource.mapper")
public class DuridOneSourceApplication {
public static void main(String[] args) { SpringApplication.run(DuridOneSourceApplication.class, args); }}Copy the code
- Create swagger configuration class
package com.bolingcavalry.druidonesource;
import springfox.documentation.service.Contact;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Tag;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/ * * *@Description: Swagger configuration class *@author: willzhao E-mail: [email protected]
* @date: 2020/8/11 when * /
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(a) {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.tags(new Tag("UserController"."User Services"), new Tag("LogController"."Log Service"))
.select()
// The current package path
.apis(RequestHandlerSelectors.basePackage("com.bolingcavalry.druidonesource.controller"))
.paths(PathSelectors.any())
.build();
}
// Build the details function of the API document, note which annotation here refers to
private ApiInfo apiInfo(a) {
return new ApiInfoBuilder()
// Page title
.title("MyBatis CURD operation")
/ / founder
.contact(new Contact("Programmer Chen"."https://github.com/zq2599/blog_demos"."[email protected]"))
/ / version number
.version("1.0")
/ / description
.description("API description") .build(); }}Copy the code
- Druid datasource = druid datasource = druid datasource = druid datasource
package com.bolingcavalry.druidonesource;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/ * * *@Description: druid configuration class *@author: willzhao E-mail: [email protected]
* @date: 2020/8/18 08:12 * /
@Configuration
public class DruidConfig {
private static final Logger logger = LoggerFactory.getLogger(DruidConfig.class);
@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.druid.initial-size}")
private int initialSize;
@Value("${spring.datasource.druid.max-active}")
private int maxActive;
@Value("${spring.datasource.druid.min-idle}")
private int minIdle;
@Value("${spring.datasource.druid.max-wait}")
private int maxWait;
@Value("${spring.datasource.druid.pool-prepared-statements}")
private boolean poolPreparedStatements;
@Value("${spring.datasource.druid.max-pool-prepared-statement-per-connection-size}")
private int maxPoolPreparedStatementPerConnectionSize;
@Value("${spring.datasource.druid.time-between-eviction-runs-millis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.druid.min-evictable-idle-time-millis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.druid.max-evictable-idle-time-millis}")
private int maxEvictableIdleTimeMillis;
@Value("${spring.datasource.druid.validation-query}")
private String validationQuery;
@Value("${spring.datasource.druid.test-while-idle}")
private boolean testWhileIdle;
@Value("${spring.datasource.druid.test-on-borrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.druid.test-on-return}")
private boolean testOnReturn;
@Value("${spring.datasource.druid.filters}")
private String filters;
@Value("{spring.datasource.druid.connection-properties}")
private String connectionProperties;
/** * Druid connection pool configuration */
@Bean
public DruidDataSource dataSource(a) {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setMaxEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (Exception e) {
logger.error("druid configuration initialization filter", e);
}
datasource.setConnectionProperties(connectionProperties);
returndatasource; }}Copy the code
- The following data entity class, MAPper configuration, Mapper interface class, business code, etc., in addition to the package is not the same, the other and the previous chapter “MyBatis primary actual war ii: add, delete, change and check” exactly the same, please refer to github source code or the previous article to write, here will not take up the space;
Unit testing (special attention)
When unit testing, a special concern is to turn off the monitoring function, otherwise the unit test will fail;
- Create a new file named application-test.yml with the same contents as application-.yml except for the values in the red box below:
- The unit test class UserControllerTest is the same as that in the previous chapter. The red box is added to specify the use of the application-test.yml configuration file:
Validation, unit testing
The operations in the red box below can complete the unit test:
Validation, swagger
- Start the application running DuridOneSourceApplication classes;
- Browser: http://localhost:8080/swagger-ui.htm, the operation is as follows:
Select * from primary key where ID = 1;
- Other interfaces can also be completed on swagger page by similar operations;
Verify that the Druid connection pool is used
- Spring boot datasource = druid datasource = druid datasource = druid datasource = druid datasource = druid datasource = druid datasource = druid datasource View data source instance;
- Put a breakpoint on the insertWithFields method of the UserMapper interface, as shown in the red box:
3. The diagram below, click the right mouse button on the DuridOneSourceApplication class, choose the option in the red box, namely to debug ways to start the application:
4. The startup log is displayed in the red box below, indicating that the startup speed is slow in debug mode. Please wait patiently:
Druid = druid; druid = druid; druid = druid; druid = druid;
6. The project curd does not use Druid, so let’s break it to see what the data source looks like.
Experience druid’s monitoring page
- Start the application execution DuridOneSourceApplication classes;
- Browser visit: http://localhost:8080/druid, the following diagram, account password is admin (in application. The configuration of yml) :
- SQL > select * from ‘swagger’; SQL > select * from ‘Swagger’;
- Springboot + Mybatis + Druid integration development and verification is complete, I hope this article can give you some reference;
You are not alone, Xinchen original accompany all the way
- Java series
- Spring series
- The Docker series
- Kubernetes series
- Database + middleware series
- The conversation series
Welcome to pay attention to the public number: programmer Xin Chen
Wechat search “programmer Xin Chen”, I am Xin Chen, looking forward to enjoying the Java world with you…
Github.com/zq2599/blog…