Spring Boot多数据源配置

这里的案例使用的 mysql数据源以及clickHouse数据源

创建Spring Boot项目引入依赖


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.4.7version>
        <relativePath/> 
    parent>
    <groupId>com.mngroupId>
    <artifactId>demoartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>demoname>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webfluxartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        <dependency>
            <groupId>ru.yandex.clickhousegroupId>
            <artifactId>clickhouse-jdbcartifactId>
            <version>0.3.1version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.2.5version>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.4.0version>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-configuration-processorartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>io.projectreactorgroupId>
            <artifactId>reactor-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombokgroupId>
                            <artifactId>lombokartifactId>
                        exclude>
                    excludes>
                configuration>
            plugin>
        plugins>
    build>

project>

书写application.yml

#配置多数据源
spring:
  firstdatasource:
    primary:
      username: test
      password: test
      url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
      driver-class-name: com.mysql.cj.jdbc.Driver
  seconddatasouce:
    secondary:
      username: test
      password: test
      url: jdbc:clickhouse://localhost:8123/test
      driver-class-name: ru.yandex.clickhouse.ClickHouseDriver

书写与配置文件对应的实体类

@Data
public class MysqlDataSource {
    private String url;
    private String username;
    private String password;
    private String driverClassName;
}

数据源配置

多数据源配置的时候注意,必须要有⼀个主数据源
必须建立指定的目录 classpath:mapper//*Mapper.xml 写一个空的xml即可
classpath:cmapper/
/*Mapper.xml 写一个空的xml即可
@NestedConfigurationProperty
private MysqlDataSource primary; 这个primary就是我们在配置文件中除去spring.firstdatasource后边的那个对象

@Configuration
@MapperScan(basePackages = MySqlDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "mysqlSqlSessionFactory")
@ConfigurationProperties(value = "spring.firstdatasource",ignoreUnknownFields = false,ignoreInvalidFields = true)
public class MySqlDataSourceConfig {


    /**
     * 精确到 ck ⽬录,以便跟其他数据源隔离
     */
    static final String PACKAGE = "com.mn.**.mapper";
    static final String MAPPER_LOCATION = "classpath:mapper/**/*Mapper.xml";


    @NestedConfigurationProperty
    private MysqlDataSource primary;

    public MysqlDataSource getPrimary() {
        return primary;
    }

    public void setPrimary(MysqlDataSource primary) {
        this.primary = primary;
    }

    /**
     * 设置主数据源
     *
     * @return
     */
    @Bean(name = "mysqlDataSource")
    @Primary
    public DataSource mysqlDataSource() {
        DruidDataSource source = new DruidDataSource();
        source.setUsername(primary.getUsername());
        source.setPassword(primary.getPassword());
        source.setUrl(primary.getUrl());
        source.setDriverClassName(primary.getDriverClassName());
        return source;
    }

    /**
     * 为这个数据源设置事务管理
     */
    @Bean(name = "mysqlDataSourceTransactionManager")
    @Primary
    public DataSourceTransactionManager mysqlDataSourceTransactionManager() {
        return new DataSourceTransactionManager(mysqlDataSource());
    }
    /**
     * 设置mybatis的模版
     */
    @Bean(name = "mysqlSqlSessionFactory")
    @Primary
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mysqlDataSource") DataSource mysqlDataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
        mybatisConfiguration.setCallSettersOnNulls(true);
        mybatisConfiguration.setJdbcTypeForNull(JdbcType.NULL);
        mybatisConfiguration.addInterceptor(new PaginationInterceptor());
        bean.setConfiguration(mybatisConfiguration);
        bean.setDataSource(mysqlDataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MySqlDataSourceConfig.MAPPER_LOCATION));
        return bean.getObject();
    }

}
@Configuration
@MapperScan(basePackages = CkDataSourceConfig.PACKAGE, sqlSessionFactoryRef= "ckSqlSessionFactory")
@ConfigurationProperties(value = "spring.seconddatasouce",ignoreUnknownFields = false,ignoreInvalidFields = true)
public class CkDataSourceConfig {

    /**
     * 精确到 primary ⽬录,以便跟其他数据源隔离
     */
    static final String PACKAGE = "com.mn.**.cmapper";
    static final String MAPPER_LOCATION = "classpath:cmapper/**/*.xml";


    @NestedConfigurationProperty
    private MysqlDataSource secondary;

    public MysqlDataSource getSecondary() {
        return secondary;
    }

    public void setSecondary(MysqlDataSource secondary) {
        this.secondary = secondary;
    }

    /**
     * 设置主数据源
     *
     * @return
     */
    @Bean(name = "ckDataSource")
    public DataSource ckDataSource() {
        DruidDataSource source = new DruidDataSource();
        source.setUsername(secondary.getUsername());
        source.setPassword(secondary.getPassword());
        source.setUrl(secondary.getUrl());
        source.setDriverClassName(secondary.getDriverClassName());
        return source;
    }

    /**
     * 为这个数据源设置事务管理
     */
    @Bean(name = "ckDataSourceTransactionManager")
    public DataSourceTransactionManager ckDataSourceTransactionManager(@Qualifier("ckDataSource") DataSource ckDataSource) {
        return new DataSourceTransactionManager(ckDataSource);
    }


    /**
     * 设置mybatis的模版
     */
    @Bean(name = "ckSqlSessionFactory")
    public SqlSessionFactory ckSqlSessionFactory(@Qualifier("ckDataSource") DataSource ckDataSource) throws Exception {

        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
        mybatisConfiguration.setCallSettersOnNulls(true);
        mybatisConfiguration.setJdbcTypeForNull(JdbcType.NULL);
        mybatisConfiguration.addInterceptor(new PaginationInterceptor());
        bean.setConfiguration(mybatisConfiguration);
        bean.setDataSource(ckDataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(CkDataSourceConfig.MAPPER_LOCATION));
        return bean.getObject();
    }


}

你可能感兴趣的:(springboot)