Springboot项目配置多数据源,然后任意切换

数据库信息

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/xxl_job_test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.second.url=jdbc:mysql://127.0.0.1:3306/dynamic02?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai
spring.datasource.second.username=root
spring.datasource.second.password=root

spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver

### datasource-pool
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.minimum-idle=10
spring.datasource.hikari.maximum-pool-size=30
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=HikariCP
spring.datasource.hikari.max-lifetime=900000
spring.datasource.hikari.connection-timeout=10000
spring.datasource.hikari.connection-test-query=SELECT 1
spring.datasource.hikari.validation-timeout=1000

  启动类设置

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class XxlJobAdminApplication {

	public static void main(String[] args) {
        SpringApplication.run(XxlJobAdminApplication.class, args);
	}

}

  配置类

package com.xxl.job.admin.core.conf;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
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 javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {


    @Value("${spring.datasource.driverClassName}")
    private String driverClassName;

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String userName;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.second.url}")
    private String secondUrl;

    @Value("${spring.datasource.second.username}")
    private String secondUserName;

    @Value("${spring.datasource.second.password}")
    private String secondPassword;

    @Value("${spring.datasource.hikari.minimum-idle}")
    private int minimumIdle;
    @Value("${spring.datasource.hikari.maximum-pool-size}")
    private  int maxPoolSize;
    @Value("${spring.datasource.hikari.auto-commit}")
    private boolean isAutoCommit;
    @Value("${spring.datasource.hikari.idle-timeout}")
    private  int minIdleTimeOut;
    @Value("${spring.datasource.hikari.pool-name}")
    private String poolName;
    @Value("${spring.datasource.hikari.max-lifetime}")
    private  long maxLifetime;
    @Value("${spring.datasource.hikari.connection-timeout}")
    private long conectionTimeOut;
    @Value("${spring.datasource.hikari.connection-test-query}")
    private String connectionTestQuery;
    @Value("${spring.datasource.hikari.validation-timeout}")
    private  long validationTimeout;


    @Bean("old_ds")
    public DataSource oldDataSource() {
        HikariConfig config = new HikariConfig();
        config.setDriverClassName(driverClassName);
        config.setJdbcUrl(url);
        config.setUsername(userName);
        config.setPassword(password);
        config.setMinimumIdle(minimumIdle);
        config.setMaximumPoolSize(maxPoolSize);
        config.setAutoCommit(isAutoCommit);
        config.setIdleTimeout(minIdleTimeOut);
        config.setPoolName(poolName);
        config.setMaxLifetime(maxLifetime);
        config.setConnectionTimeout(conectionTimeOut);
        config.setConnectionTestQuery(connectionTestQuery);
        config.setValidationTimeout(validationTimeout);
        HikariDataSource dataSource = new HikariDataSource(config);
        return dataSource;
    }

    private DataSource newDataSource() {
        HikariConfig config = new HikariConfig();
        config.setDriverClassName(driverClassName);
        config.setJdbcUrl(secondUrl);
        config.setUsername(secondUserName);
        config.setPassword(secondPassword);
        config.setMinimumIdle(minimumIdle);
        config.setMaximumPoolSize(maxPoolSize);
        config.setAutoCommit(isAutoCommit);
        config.setIdleTimeout(minIdleTimeOut);
        config.setPoolName(poolName);
        config.setMaxLifetime(maxLifetime);
        config.setConnectionTimeout(conectionTimeOut);
        config.setConnectionTestQuery(connectionTestQuery);
        config.setValidationTimeout(validationTimeout);
        HikariDataSource dataSource = new HikariDataSource(config);
        return dataSource;
    }

    /**
     * 设置动态数据源为主数据源
     *
     * @return
     */
    @Bean
    @Primary
    public DataSource dataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DBMigrationContext.OLD_DS_KEY, oldDataSource());
        targetDataSources.put(DBMigrationContext.NEW_DS_KEY, newDataSource());
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.afterPropertiesSet();
        return dynamicDataSource;
    }


}

  

package com.xxl.job.admin.core.conf;

public class DBMigrationContext {
    public static final String OLD_DS_KEY = "old_ds";
    public static final String NEW_DS_KEY = "new_ds";
    private static volatile String CURRENT_DS = OLD_DS_KEY;

    public static String getCurrentDs() {
        return CURRENT_DS;
    }

    public static void setCurrentDs(String currentDs) {
        CURRENT_DS = currentDs;
    }
}

  

package com.xxl.job.admin.core.conf;


import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * @Description:
 * @Author: 喵星人
 * @Create: 2023/12/4 9:50
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return DBMigrationContext.getCurrentDs();
    }

}

  

package com.xxl.job.admin.core.scheduler;

import com.xxl.job.admin.core.thread.JobDatasourceSwitchHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

/**
 * @Description:
 * @Author: 喵星人
 * @Create: 2023/12/11 13:56
 */
@Component
public class XxlDataSourceSwitvhScheduler {


    @Autowired
    private Environment environment;

    @PostConstruct
    public void init() throws Exception {

        new JobDatasourceSwitchHelper(environment.getProperty("datasource.switch.start.time"),environment.getProperty("datasource.switch.between.time")).start();

    }
}

  

这里切换数据源
DBMigrationContext.setCurrentDs(DBMigrationContext.NEW_DS_KEY);

  

posted @ 2024-01-17 11:03  不忘初心2021  阅读(197)  评论(0编辑  收藏  举报