springboot集成HikariDataSource数据源

编程

1、编辑配置文件

spring.datasource.name=xx-datasource
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://xx:3306/xx?useUnicode=true&characterEncoding=UTF-8
  &zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true&autoReconnect=true&failOverReadOnly=false
  &maxReconnects=10&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.readOnly=false
spring.datasource.connectionTimeout=60000
spring.datasource.idleTimeout=600000
spring.datasource.validationTimeout=3000
spring.datasource.loginTimeout=5
spring.datasource.maxLifetime=700000
spring.datasource.maximumPoolSize=100

 

2、上代码

 

import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import com.zaxxer.hikari.HikariDataSource;
 

@Configuration
public class DataSourceConfig {

    @Bean(name = "dataSource")
    public DataSource datasource(Environment env) throws NumberFormatException, SQLException {
        HikariDataSource ds = new HikariDataSource();
        ds.setDriverClassName(env.getProperty("spring.datasource.driverClassName"));
        ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
        ds.setUsername(env.getProperty("spring.datasource.username"));
        ds.setPassword(env.getProperty("spring.datasource.password"));
        ds.setReadOnly(Boolean.parseBoolean(env.getProperty("spring.datasource.readOnly")));
        ds.setConnectionTimeout(Long.parseLong(env.getProperty("spring.datasource.connectionTimeout")));
        ds.setIdleTimeout(Long.parseLong(env.getProperty("spring.datasource.idleTimeout")));
        ds.setValidationTimeout(Long.parseLong(env.getProperty("spring.datasource.validationTimeout")));
        ds.setLoginTimeout(Integer.parseInt(env.getProperty("spring.datasource.loginTimeout")));
        ds.setMaxLifetime(Long.parseLong(env.getProperty("spring.datasource.maxLifetime")));
        ds.setMaximumPoolSize(Integer.parseInt(env.getProperty("spring.datasource.maximumPoolSize")));
        return ds;
    }

}

以上是 springboot集成HikariDataSource数据源 的全部内容, 来源链接: utcz.com/z/519075.html

回到顶部