spring-boot learning: 7. Default configuration of database connection

Posted by pandaweb on Tue, 10 Sep 2019 11:26:27 +0200

To learn a knowledge point, the first thing is to check the official documents:

https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/htmlsingle/#boot-features-sql


Spr-boot chooses HikariCP (known as the fastest and most powerful) as the default connection pool. Here's how to use it:

1. Introducing jar packages into pom.xml

<!-- Use the default jdbc Connection pool HikariCP -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
    
<!-- spring-boot Default version, 2.1.6.RELEASE Correspondence 8.0.16   -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

2. Add mysql configuration in application.properties:

# mysql
spring.datasource.url=jdbc:mysql://localhost:3306/springboot2
spring.datasource.username=kevin
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

3. Start up the application

The following errors will occur when starting directly according to the above configuration:

Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class iscom.mysql.cj.jdbc.Driver'. The driver is
automatically registered via the SPI and manual loading of the driver
class is generally unnecessary.

This means that com.mysql.jdbc.Driver is obsolete and needs to use com.mysql.cj.jdbc.Driver (mysql-connector-java 6 or more uses this driver class), and springboot will automatically join; so we just need to remove the spring.datasource.driver-class-name configuration or set it to com.mysql.cj.jdbc.Driver, and restart it. Just move.

4. Test whether jdbc is connected (add a record manually to the database for testing)

package com.kevin.springbootstudy.controller;

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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JdbcController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping(value = "getUser")
    public Object getUser(@RequestParam(value = "id")String id){
        return jdbcTemplate.queryForObject("select name from user where id = ?", new String[]{id}, String.class);
    }

}

Test http://localhost:8081//user?id=1 error:

java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is
unrecognized or represents more than one time zone. (that is mysql Connections need to configure time zones)

1) Modify database connections

spring.datasource.url=jdbc:mysql://localhost:3306/springboot2?characterEncoding=utf8&serverTimezone=UTC

Visit http://localhost:8081/getUser?id=1 and return kevin. The test is successful

View background log printing to show that HikariPool database connection pool started successfully

2019-09-09 10:14:55.884  INFO 9432 --- [nio-8081-exec-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting... 
2019-09-09 10:14:56.243  INFO 9432 --- [nio-8081-exec-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.

2) Check whether the time zone is correct

@RequestMapping("/dbtime")
public Object dbtime(){
    SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return format.format(jdbcTemplate.queryForObject("select now() ", Date.class));
}

Visit http://127.0.0.1:8081/dbtime and find that the return time is 8 hours longer than the actual time.

3) Restore normal after modifying the database connection property serverTimezone=Asia/Shanghai
SerrTimezone = GMT% 2B8 can also be used (GMT+8)

5. The above database connection configurations are all basic parameters. What if the connection timeout time and the maximum number of connections in the connection pool are also set?

Refer to Hikari's detailed configuration (https://github.com/brettwooldridge/HikariCP)


You can refer to the following configuration

# hikari

## default true default automatic submission
spring.datasource.hikari.auto-commit=true
## lowest 250 ms. Default: 30000 (30 seconds) connection timeout, minimum 250 ms, default 30 seconds
spring.datasource.hikari.connection-timeout=300
## This set only applies when minimum Idle is defined to be less than maximumPoolSize. Free connection lifetime, default 10 minutes, must be set at minimumIdle to be more effective than maximumPoolSize
spring.datasource.hikari.idle-timeout=600000
## We strongly recommend setting this value, and it should be several seconds shorter than any database or infrastructure imposed connection time limit.
## Default: 1800000 (30 minutes)
spring.datasource.hikari.max-lifetime=1800000
## If your driver supports jdbc 4 we strongly recommend not setting this property. Default: none under jdbc does not recommend setting test sql queries, default is empty
#spring.datasource.hikari.connection-test-query= select 1
## We recommend not to set this value. Default: same as maximumPoolSize does not recommend setting the minimum number of idle connections. The default is the same as the maximum number of connections.
#spring.datasource.hikari.minimum-idle=
## Default: 10 Max connections, default 10
spring.datasource.hikari.maximum-pool-size=10

Expansion:
mysql-connector-java encounters many problems, so research
https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-versions.html

1. Support for mysql version

2. Support for java version

3. maven introduces specifications

4. Use in spring

5. SerrTimezone parameter must be added when connecting

6. Common configuration parameters

Refer to https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-reference-configuration-properties.html

useUnicode (set true in 5.1 to use characterEncoding, which is not available in 8.0)
characterEncoding
autoReconnect
Whether the connection is set to read-only after failOverReadOnly auto-reconnection is successful
Number of retries for maxReconnects
serverTimezone
useSSL (For 8.0.13 and later: Default is 'true')
rewriteBatchedStatements opens batch processing and does not open by default

7. Driver name

8.0 Driver Name:

Driver name of 5.1

Topics: Spring MySQL JDBC Database