Springboot MySQL template multi data source loading

Posted by mj_23 on Sun, 27 Oct 2019 02:45:40 +0100

qq communication group: 812321371
Wechat communication group: mercy Yao

brief introduction

mysql multi data source operation is often used in java projects. It is very convenient to use the original one in combination with spring boot.
However, you need to configure multiple data source configurations.

In microservices, the configuration of database connection is to separate and read. Equivalent to a template.

As follows: mysql:

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/${config.mysql.name}?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&autoReconnect=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.jdbc.Driver

The connection configuration of redis rabbitmq mongodb and other middleware is separated by a separate configuration, so as to facilitate the subsequent modification of connection information such as ip.

Of course, spring boot needs to read the data configuration of the corresponding prefix when injecting multiple data sources.

Code:

@Bean
@ConfigurationProperties(prefix = "spring.datasource.onemysql")
public DataSource originalDataSource(DataSourceFactory dataSourceFactory) {
    return DataSourceBuilder.create().build();
}

To configure:

spring.datasource.onemysql.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.onemysql.url=jdbc:mysql://127.0.0.1:3306/${config.mysql.name}?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&autoReconnect=true
spring.datasource.onemysql.username=root
spring.datasource.onemysql.password=root
spring.datasource.onemysql.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.onemysql.driverClassName=com.mysql.jdbc.Driver

Load the data source configuration starting with onemysql as above. If multiple, configure multiple bean s and configuration files accordingly.

According to the above method, we can use a mysql template to load and create the corresponding data source in a certain way. Only one mysql configuration template needs to be maintained under microservice.

Function use

Add dependency

ps: please use the latest version for the actual version
Latest version:

Click to view the latest version

<dependency>
  <groupId>com.purgeteam</groupId>
  <artifactId>mysql-datasource-spring-boot-starter</artifactId>
  <version>0.1.0.RELEASE</version>
</dependency>

1 configuration template

We first configure mysql data source configuration in the original way.

config.mysql.name=user
config.mysql.hosturl=127.0.0.1:3306

# mysql
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://${config.mysql.hosturl}/${config.mysql.name}?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&autoReconnect=true
spring.datasource.jdbc-url=${spring.datasource.url}
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.filters=stat
spring.datasource.maxActive=20
spring.datasource.initialSize=1
spring.datasource.maxWait=60000
spring.datasource.minIdle=1
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=select 'x'
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxOpenPreparedStatements=20

config.mysql.name is the database name, preparing for the following code injection.

2. Database name combined with template configuration

The datasourcefactory ා createdatasource method can inject the specified database. The template is configured as the previous configuration, and the database name is replaced by ${config.mysql.name}.

/**
 * Generate {@ link DataSource} by replacing database name
 * @author purgeyao
 * @since 1.0
 */
@Configuration
public class OneDataSourceConfiguration {

    ...

    /**
     * DataSourceFactory#createDataSource Load one MySQL database by
     * @param dataSourceFactory dataSourceFactory
     * @return {@link DataSource}
     */
    @Primary
    @Bean
    public DataSource oneDataSource(DataSourceFactory dataSourceFactory) {
        return dataSourceFactory.createDataSource("one_mysql");
    }

}

In this way, you can load the data source named one MySQL database.

2 database information combination configuration template

Of course, only the above method is suitable for database address and password consistency, database name inconsistency, and injection of multiple data sources.

The following method supports the use of templates to inject multiple data sources when the database information is inconsistent.

You need to configure mysql (1 configuration template), and add the following configuration.

To configure:

config.datasource.mysql.source-info-map contains four information: host URL database address, name database name, username database user name, password database password.

In config.datasource.mysql.source-info-map.how'mysql is the key of the map set.

# mysql-datasource-spring-boot-starter
config.datasource.mysql.source-info-map.tow_mysql.host-url=127.0.0.1:3306
config.datasource.mysql.source-info-map.tow_mysql.name=tow_mysql
config.datasource.mysql.source-info-map.tow_mysql.username=root
config.datasource.mysql.source-info-map.tow_mysql.password=root

Code:

First, obtain the corresponding SourceInfoMap configuration in the DataSourceConfigProperties object.

The configuration of DataSourceConfigProperties.SourceInfo towMysq can be created by the datasourcefactory ා createdatasource method.

/**
 * {@link DataSourceConfigProperties} Generate {@ link DataSource} in configuration mode
 *
 * @author purgeyao
 * @since 1.0
 */
@Configuration
public class TowDataSourceConfiguration {

    /**
     * DataSourceFactory#createDataSource How to load the Dow MySQL database
     *
     * @param dataSourceFactory dataSourceFactory
     * @return {@link DataSource}
     */
    @Bean
    public DataSource towDataSource(DataSourceFactory dataSourceFactory, DataSourceConfigProperties properties) {
        DataSourceConfigProperties.SourceInfo towMysql = properties.getSourceInfoMap().get("tow_mysql");
        if (towMysql == null) {
            throw new IllegalArgumentException("Configuration not obtained");
        }
        return dataSourceFactory.createDataSource(towMysql);
    }

}

4 annotation selector combined with template configuration (recommended writing method)

@The DataSourceSelector annotation can generate the corresponding data source object using the configuration template.

Datasourceselector? Value configures the key for the database (configuration of detail 2). Other writing methods are consistent with the original database creation methods.

Just replace the original @ ConfigurationProperties(prefix = "spring.datasource.onemysql") with @ datasourceselector ("tow" MySQL ")

/**
 * Annotation mode injection {@ link DataSource}
 *
 * @author purgeyao
 * @since 1.0
 */
@Configuration
public class AnnotationsDataSourceConfiguration {

    ...

    /**
     * {@link DataSourceSelector} Mode selection injection {@ link DataSource}
     *
     * @return {@link DataSource}
     */
    @DataSourceSelector("tow_mysql")
    public DataSource selectorDataSource() {
        return DataSourceBuilder.create().build();
    }
}

summary

@Datasourceselector ("tow? MySQL") is recommended. It is basically the same as the previous method, simple and convenient.

After the mysql configuration file is separated, it is convenient for multiple services to use.

qq communication group: 812321371
Wechat communication group: mercy Yao

Example code address: data-source-spring-boot

By GitHub:
Purgeyao Welcome to your attention.
This article is based on the platform of blog one article multiple sending OpenWrite Release!

Topics: Java Spring MySQL Database JDBC