spring boot configuration druid connection pool mysql


Spring Boot Integration Tutorial


Outline

spring boot is now the default connection pool Hikari , claims to be the best performance of the connection pool, but more for domestic use is open source druid connection pool Ali, Ali proven in many projects, this article describes how spring boot in integrated Druid .

Prepare data

We will use the tutorial connection mysql spring boot the same data, without the data refer to the tutorial prepares the data, the tutorial details the process through graphical client workbench mysql generated data. If you tend to use the mysql command-line client, the following statement is to create a sql database and insert data.

sql statement

mysql command-line client connect to the database:

mysql -h localhost -u root -p

Create a database

CREATE DATABASE qikegu_demo CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Create a table of sql statement:

CREATE TABLE `qikegu_demo`.`user` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `nickname` VARCHAR(50) NULL COMMENT '昵称',
  `mobile` VARCHAR(20) NULL COMMENT '手机号',
  `password` CHAR(60) NULL COMMENT '密码hash值',
  `role` VARCHAR(100) NULL DEFAULT 'user' COMMENT '角色,角色名以逗号分隔',
  PRIMARY KEY (`id`),
  UNIQUE INDEX `mobile_UNIQUE` (`mobile` ASC))
COMMENT = '用户表';

Insert data sql statement:

INSERT INTO `qikegu_demo`.`user` (`nickname`, `mobile`, `password`) VALUES ('abc1', '13512345678', '123');
INSERT INTO `qikegu_demo`.`user` (`nickname`, `mobile`, `password`) VALUES ('abc2', '13512345677', '123');

Create a project

Create a spring boot project

Open Eclipse, create spring starter project spring boot of the project, when configuring dependent, check the web, jdbc, mysql, such as do not know how to create a spring boot project, referring to the tutorial: spring boot the Hello world (RESTful Interface) Examples

image

Add druid dependence

In the pom.xml file, add druid dependence

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid-spring-boot-starter</artifactId>
   <version>1.1.10</version>
</dependency>

Complete pom.xml file reads 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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.qikegu</groupId>
    <artifactId>druid-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>druid-demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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>
        </dependency>
        
        <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>druid-spring-boot-starter</artifactId>
           <version>1.1.10</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Configuration database

application.properties Configuration

Open file: application.properties, the file in the src -> main -> resourcesdirectory, configure the database connection:

# 服务器端口
server.port=8096 

# 数据库设置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/qikegu_demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=你的数据库密码

# druid配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

# druid参数调优(可选)
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
# 测试连接
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters
spring.datasource.filters=stat
# asyncInit是1.1.4中新增加的配置,如果有initialSize数量较多时,打开会加快应用启动时间
spring.datasource.asyncInit=true

See explanation of code comments. druid must in fact very little configuration, you need to configure a row, that it will not use the default Hikari , and use druid.

# druid配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

Parameter tuning section is optional, the official website druid parameters are listed here typical recommended configuration. Another monitor configuration, the general use do not let it go.

DruidConfig.java Configuration

Now that does not support druid Spring Boot configuration, configuration parameters adjustment portion preferably has no direct effect, configure datasource bean, from the read values ​​application.properties assembled datasource bean, DruidConfig.java new profile:

image

DruidConfig.java following code, reads the value in the configuration file by annotations @value

package com.qikegu.demo.config;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

@Configuration
public class DruidConfig {
    private 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.initial-size}")
    private int initialSize;
    
    @Value("${spring.datasource.min-idle}")
    private int minIdle;
    
    @Value("${spring.datasource.max-active}")
    private int maxActive;
    
    @Value("${spring.datasource.max-wait}")
    private int maxWait;
    
    @Value("${spring.datasource.time-between-eviction-runs-millis}")
    private int timeBetweenEvictionRunsMillis;
    
    @Value("${spring.datasource.min-evictable-idle-time-millis}")
    private int minEvictableIdleTimeMillis;
    
//    @Value("${spring.datasource.validation-query}")
//    private String validationQuery;
    
    @Value("${spring.datasource.test-while-idle}")
    private boolean testWhileIdle;
    
    @Value("${spring.datasource.test-on-borrow}")
    private boolean testOnBorrow;
    
    @Value("${spring.datasource.test-on-return}")
    private boolean testOnReturn;
    
    @Value("${spring.datasource.pool-prepared-statements}")
    private boolean poolPreparedStatements;
    
    @Value("${spring.datasource.max-pool-prepared-statement-per-connection-size}")
    private int maxPoolPreparedStatementPerConnectionSize;
    
    @Value("${spring.datasource.filters}")
    private String filters;
    
//    @Value("${spring.datasource.connection-properties}")
//    private String connectionProperties;
    
    @Bean     //声明其为Bean实例
    @Primary  //在同样的DataSource中,首先使用被标注的DataSource
    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 initialization filter", e);
        }
//      datasource.setConnectionProperties(connectionProperties);
        
        return datasource;
    }
}

Access database

Add code to verify whether the database is properly connected, add files: HelloController.java

image

HelloController.java code


package com.qikegu.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    @RequestMapping(value="/hello", method=RequestMethod.GET)
    public String index() {
        
        String sql = "SELECT mobile FROM user WHERE id = ?";
        
        // 通过jdbcTemplate查询数据库
        String mobile = (String)jdbcTemplate.queryForObject(
                sql, new Object[] { 1 }, String.class);
        
        return "Hello " + mobile;
    }
}

We use the spring of JdbcTemplate (this is the reason we have introduced in the previous spring jdbc-dependent), jdbc convenient than using the original interface.

run

Project context menu and select: run as -> spring boot appRun the program (do not know how to run may refer to: the Spring the Boot the Hello world (RESTful Interface) example ), use a browser to access the output read from the database of the user's phone number

image

Use of monitoring druid

druid monitoring function, through the web site: http: // localhost: 8096 / druid / index.html view.
View DataSource page, you can see our configuration really take effect:

image

to sum up

This article describes how to integrate druid connection pool in spring boot project, JdbcTemplate use to access the database, verify the database connection is successful.

The complete code

Guess you like

Origin www.cnblogs.com/jinbuqi/p/11008879.html