自学内容网 自学内容网

java 配置多数据源

介绍两种配置多数据源的方式

1.使用dynamic-datasource-spring-boot-starter来实现

(1)引入包

<dependency>  
    <groupId>com.baomidou</groupId>  
    <artifactId>dynamic-datasource-spring-boot-starter</artifactId>  
    <version>最新版本号</version>  
</dependency>

(2)application.xml中配置不同的数据源

spring:  
  datasource:  
    dynamic:  
      primary: mysql # 设置默认的数据源或者数据源组,默认值为master  
      datasource:  
        mysql:  
          url: jdbc:mysql://localhost:3306/masterdb  
          username: root  
          password: 123456  
          driver-class-name: com.mysql.cj.jdbc.Driver  
        clickhouse:  
          url: jdbc:clickhouse://localhost:21424/his?socket_timeout=80000  
          username: root  
          password: 123456  
          driver-class-name: ru.yandex.clickhouse.ClickHouseDriver
          type: com.alibaba.druid.pool.DruidDataSource  
      # ... 其他配置

(3)使用 @DS 注解切换数据源

在需要进行数据源切换的 Mapper 接口或者 Service 方法上,使用 @DS 注解来指定需要使用的数据源。如果没有指定,则使用默认的数据源。

@Mapper
@DS("mysql")  
public interface UserMapper {  
    
}

@Mapper
@DS("clickhouse")  
public interface StatisticsMapper {  
    
}

2.使用mybatis配置多数据源

(1)application.properties自定义配置

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#mysql配置
spring.datasource.mysql.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.mysql.url=jdbc:mysql://localhost:3306/wotou?servertimezone=Asia?Shanghai&useUnicode=true&charaterEncoding=utf-8
spring.datasource.mysql.username=root
spring.datasource.mysql.password=1234
spring.datasource.mysql.driverClassName= com.mysql.cj.jdbc.Driver
#clickhouse配置
spring.datasource.clickhouse.driverClassName=ru.yandex.clickhouse.ClickHouseDriver
spring.datasource.clickhouse.url=jdbc:clickhouse://1localhost:8123/his?socket_timeout=600000
spring.datasource.clickhouse.username=default
spring.datasource.clickhouse.password=
spring.datasource.clickhouse.initialSize=10
spring.datasource.clickhouse.maxActive=100
spring.datasource.clickhouse.minIdle=10
spring.datasource.clickhouse.maxWait=6000

(2).获取配置

@Data
@Component
@ConfigurationProperties(prefix = "spring.datasource.mysql")
public class MysqlConfig {

    private String username;

    private String url;

    private String password;

    private String driverClassName;
}
@Data
@Component
@ConfigurationProperties(prefix = "spring.datasource.clickhouse")
public class ClickHouseConfig {
    private String driverClassName;
    private String url;
    private String username;
    private String password;
    private Integer initialSize;
    private Integer maxActive;
    private Integer minIdle;
    private Integer maxWait;


}

(3)配置DataSource

@Component
@RequiredArgsConstructor
public class DataSourceConfig {

    private final MysqlConfig mysqlConfig;
    private final ClickHouseConfig clickHouseConfig;

    @Bean(name = "mysqlDataSource")
    public DataSource mysqlDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUsername(mysqlConfig.getUsername());
        druidDataSource.setPassword(mysqlConfig.getPassword());
        druidDataSource.setUrl(mysqlConfig.getUrl());
        druidDataSource.setDriverClassName(mysqlConfig.getDriverClassName());
        return druidDataSource;
    }

    @Bean(name = "clickhouseDataSource")
    public DataSource clickhouseDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(clickHouseConfig.getUrl());
        druidDataSource.setPassword(clickHouseConfig.getPassword());
        druidDataSource.setUsername(clickHouseConfig.getUsername());
        druidDataSource.setDriverClassName(clickHouseConfig.getDriverClassName());
        druidDataSource.setInitialSize(clickHouseConfig.getInitialSize());
        druidDataSource.setMaxActive(clickHouseConfig.getMaxActive());
        druidDataSource.setMinEvictableIdleTimeMillis(clickHouseConfig.getMinIdle());
        druidDataSource.setMaxWait(clickHouseConfig.getMaxWait());
        druidDataSource.setValidationQuery("SELECT 1 ");
        return druidDataSource;
    }
}

(4)配置mybatis sqlsession(这里指明了不同数据源对应的xml文件的位置)

@Component
public class MybatisSqlsessionConfig {

    @Bean(name = "mysqlSqlSessionFactory")
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mysqlDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/mysql/*.xml"));
        MybatisConfiguration configuration = new MybatisConfiguration();
        // 开启驼峰命名法转换
        configuration.setMapUnderscoreToCamelCase(true);
        //打印日志
        configuration.setLogImpl(StdOutImpl.class);
        sqlSessionFactoryBean.setConfiguration(configuration);
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "clickhouseSqlSessionFactory")
    public SqlSessionFactory clickhouseSqlSessionFactory(@Qualifier("clickhouseDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/clickhouse/*.xml"));
        MybatisConfiguration configuration = new MybatisConfiguration();
        // 开启驼峰命名法转换
        configuration.setMapUnderscoreToCamelCase(true);
        //打印日志
        configuration.setLogImpl(StdOutImpl.class);
        sqlSessionFactoryBean.setConfiguration(configuration);
        return sqlSessionFactoryBean.getObject();
    }
}

(5)配置对应的mapper接口对应的数据源

@SpringBootApplication
@MapperScan(basePackages = "com.xxx.mapper.mysql", sqlSessionFactoryRef = "mysqlSqlSessionFactory")
@MapperScan(basePackages = "com.xxx.mapper.clickhouse", sqlSessionFactoryRef = "clickhouseSqlSessionFactory")
public class WotouApplication {
    public static void main(String[] args) {
        SpringApplication.run(WotouApplication.class,args);
    }
}


原文地址:https://blog.csdn.net/wenlai123456/article/details/141130627

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!