开发者

Springboot结合JDBC实现双数据源实例

开发者 https://www.devze.com 2023-12-11 10:24 出处:网络 作者: 慈祥的茶壶
目录配置文件配置类创建controller测试配置文件 spring: application: name: tuberculosis datasource:
目录
  • 配置文件
  • 配置类
  • 创建controller测试

配置文件

spring:
  application:
    name: tuberculosis
  datasource:
    tuberculosis:
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://127.0.0.1:3306/tuberculosis?useUnicode=true&characterEncoding=utf8&useSSL=false
      username: root
      password: root
      type: com.zaxxer.hikari.HikariDataSource
      hikari:
        minimum-idle: 5
        maximum-pool-size: 100
        auto-commit: true
        idle-timeout: 30000
        pool-name: DatabookHikariCP
        max-lifetime: 1800000
        connection-timeout编程客栈: 30000
        connection-test-query: SELECT 1
    jkjc:
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://127.0.0.1:3306/jkjc?useUnicode=true&characterEncoding=utf8&useSSL=false
      username: root
      password: root
      type: com.zaxxer.hikari.HikariDataSource
      hikari:
        minimum-idle: 5
        maximum-pool-size: 100
        auto-commit: true
        idle-timeout: 30000
        pool-name: DatabookHikariCP
        max-lifetime: 1800000
        connection-timeout: 30000
        connection-test-query: SELECT 1

注意:单个数据库的配置为url,而在多个数据源的时候url可能启动会报错,需要使用jdbc-url

配置类

package com.daryl.config.db;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import Javax.sql.DataSource;
import java.util.HashMap;
/**
 * @author daryl
 * @create 2023/12/08
 */
@Component
public class DataSourceConfig {
    @Bean(name = "tuberculosis")
    @ConfigurationProperties(prefix = "spring.datasource.tuberculosis")
    public DataSource dataSourceOne() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "jkjc")
    @ConfigurationProperties(prefix = "spring.datasource.jkjc")
    public DataSource dataSourceTwo() {
        return DataSourceBuilder.create().build();
    }
    @Bean("dynamicDatasource")
    @Primary
    public DataSource dynamicDataSource(@Qualifier("tuberculosis") DataSource tuberculosis,@Qualifier("jkjc") DataSource jkjc) {
        DynamicDatasource dynamicDatasource = new DynamicDatasource();
        dynamicDatasource.setDefaultTargetDataSource(tuberculosis);
        HashMap<Object, Object> dsMap = new HashMap<>();
        dsMap.put("tuberculosis", tuberculosis);
        dsMap.put("jkjc", jkjc);
        dynamicDatasource.setTargetDataSources(dsMap);
        return dynamicDatasource;
    }
    @Bean
    public PlatformTransactionManager transactionManager(@Qualifier("dynamicDatasource") DataSource dynamicDatasource) {
        return new 编程客栈DataSourceTransactionManager(dynamicDatasource);
    }
}
package com.daryl.config.db;
/**
 * @ajsuthor daryl
 * @create 2023/12/08
 */
public class DatasourceUtil {
    private static final ThreadLocal<String>www.devze.com; contextHolder = new ThreadLocal<String>();
    public static void setDB(String dbType) {
        contextHolder.set(dbType);
    }
    public static String getDB() {
        return contextHolder.get();
    }
    public static void clearDB() {
        contextHolder.remove();
    }
}
package com.daryl.config.db;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
 * @author daryl
 * @create 2023/12/08
 */
public class DynamicDatasource extends AbstractRoutingDataSource {
    private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDatasource.class);
    @Override
    protected Object determineCurrentLookupKey() {
        LOGGER.debug("动态获取数据源{}",DatasourceUtil.getDB());
        return DatasourceUtil.getDB();
 javascript   }
}

创建controller测试

@RequestMapping("/db1")
    public Object db1(@RequestBody HashMap<String, String> map) {
        //db1的用户表
        return userMapper.selectById(map.get("id"));
    }
@RequestMapping("/DB2")
    public Object db2() {
        DatasourceUtil.setDB("jkjc");
        //db2的任务表
        AssessmentTaskEntity assessmentTaskEntity = assessmentTaskMapper.selectById("1");
        DatasourceUtil.clearDB();
        User user = userMapper.selectById("1");
        System.out.println("user = " + user);
        return assessmentTaskEntity;
    }

以上就是Springboot结合JDBC实现双数据源实例的详细内容,更多关于Springboot JDBC双数据源的资料请关注编程客栈(www.devze.com)其它相关文章!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号