首页 > 其他分享 >Springboot项目配置多数据源,然后任意切换

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

时间:2024-01-17 11:11:38浏览次数:29  
标签:Springboot spring Value private hikari datasource 数据源 config 切换

数据库信息

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);

  

标签:Springboot,spring,Value,private,hikari,datasource,数据源,config,切换
From: https://www.cnblogs.com/q202105271618/p/17931253.html

相关文章

  • 基于SpringBoot+Vue的校园招聘系统设计实现(源码+lw+部署文档+讲解等)
    (文章目录)前言:heartpulse:博主介绍:✌全网粉丝10W+,CSDN特邀作者、博客专家、CSDN新星计划导师、全栈领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战✌:heartpulse:......
  • SpringBoot项目从0到1配置logback日志打印
    转载自:SpringBoot项目从0到1配置logback日志打印,作者sum墨一、写文背景我们在写后端项目的时候,日志打印是必需的。支持SpringBoot项目的日志框架一般有log4j、logback,这二者各有优劣,这里就不展开对比了。我们项目中常用的是logback框架,该框架主要是一个logback-spring.xml配置......
  • SpringBoot使用jwt实现接口带令牌访问
    1、 添加依赖<dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>${jwt.version}</version></dependency>2、先定义一个用户实体@Data@TableName("t_user")publicclass......
  • 通过Power BI实现数据的实时刷新与展示2-使用Python Code无限实时刷新数据源
    上一篇讲了使用DirectQueryMode来实现数据自动刷新,但是DirectMode只能适用于Database这种数据源,很多其它的源都不行。对于其它类型的数据源,就只能另想办法了。PBI刷新可以用以下2种方式:1,在PBIDesktop中点击刷新,然后刷新完成后,再Publish2,将报告发布到WorkSpace中,然后在选中D......
  • Springboot3+Vue3在进行WebSocket通讯时出现No mapping for GET或者是404
    参考:在SpringBoot中整合、使用WebSocket-spring中文网(springdoc.cn)===============================原代码(此时前端访问后端,后端会出现:NomappingforGET/wspath)前端相关代码:letsocket:WebSocket|null=nullconstsocketURL=`ws://127.0.0.1:8084/w......
  • 实现手机/PC端滑块验证(VUE+Springboot)
    思路a,通过后端,获取到图片,这个图片自己定义,随便是撒。b,通过代码把图片进行随机抠图,扣出一块,形成第二个图,该小图就是为了合并到原有的窟窿中。c,然后把两个图传到后端,保存抠出的图需要移动的距离到redis,作为验证值。d,前端根据图的位置展示底图与小图e,进行移动,完成后进行验证。......
  • springBoot通过AOP(面向切面编程)实现自动保存请求日志
    1.定义注解importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;@Target(ElementType.METHOD)//指定该注解只能应用于方法上@Retention(RetentionPolicy.......
  • springboot~shardingsphere在非spring框架中的使用
    shardingsphere已经很方便的被springboot集成了,你只要引入sharding-jdbc-spring-boot-starter这个包就可以了,而如果是原生java的话,你就需要自己去实现了,主要是重新定义数据源,定义规则等问题,本文主要介绍原生环境下的shardingsphere的使用。依赖引用<dependencies><!--......
  • springboot第48集:【思维导图】地图,面向对象,异常,功能代码
    在SpringBoot中,可以通过编写拦截器(Interceptor)来对请求进行拦截与处理。下面是一个简单的拦截器实现示例:创建一个类并实现HandlerInterceptor接口publicclassAuthInterceptorimplementsHandlerInterceptor{@OverridepublicbooleanpreHandle(HttpServletRequest......
  • Springboot上传文件大小限制处理
    今天在开发过程中遇到一个文件上传的问题io.undertow.server.RequestTooBigException:UT000020:Connectionterminatedasrequestwaslargerthan10485760Servlet容器使用的是undertow,看异常信息应该是默认存在10MB的文件大小限制。百度了一下,找到如下配置,问题得以解决,记......