Spring boot 双数据源实例

 最开始写这个项目也是临时磨刀,需求事要从sqlserver数据库中把数据导入到mysql中,中间还是踩了个坑。

开始想着是使用 kettle 进行数据抽取,但是看了半天kettle抽取其实也相对麻烦,对于数据库得校验,数据得校验等,可能我了解的也不够透彻。这个暂时不提   进入正题。

写的时候最开始想到了springboot   毕竟现在初始化一个项目十分容易并且对大多数功能有较好得支持。下面个截图是我得整个项目结构,中间还是熟悉得controller->service->impl->mapper        

 这个是配置文件  直接粘贴出来了

master.datasource.url=
master.datasource.username=
master.datasource.password=
master.datasource.driverClassName=com.mysql.cj.jdbc.Driver

cluster.datasource.url=
cluster.datasource.username=
cluster.datasource.password=
cluster.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.initialSize=5  
spring.datasource.minIdle=5  
spring.datasource.maxActive=20  

spring.datasource.maxWait=60000  

spring.datasource.timeBetweenEvictionRunsMillis=60000  

spring.datasource.minEvictableIdleTimeMillis=300000  
spring.datasource.validationQuery=SELECT 1 FROM DUAL  
spring.datasource.testWhileIdle=true  
spring.datasource.testOnBorrow=false  
spring.datasource.testOnReturn=false  

spring.datasource.poolPreparedStatements=true  
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20  

spring.datasource.filters=stat,wall,log4j  

spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
#日志相关配置
logging.file.name=classpath:logback-spring.xml
#logging.file.path=E:/
logging.file.path=/home/logs/transmission
logging.level.root=INFO
logging.level.com.example.transmission.msdata.product.mapper = DEBUG
logging.level.com.example.transmission.mssdata.product.mapper = DEBUG

配置文件中master   cluster  对应项目结构中

@Configuration
//扫描 Mapper 接口并容器管理
@MapperScan(basePackages = {"com.example.transmission.mssdata"}, sqlSessionFactoryRef = "clusterSqlSessionFactory")
public class ClusterDataSourceConfig {

    // 精确到 cluster 目录,以便跟其他数据源隔离
    static final String PACKAGE = "com.example.transmission.mssdata";
    static final String MAPPER_LOCATION = "classpath:mapper/mssdata/*/*.xml";

    @Value("${cluster.datasource.url}")
    private String url;
 
    @Value("${cluster.datasource.username}")
    private String user;

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

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

    @Bean(name = "clusterDataSource")
    public DataSource clusterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "clusterTransactionManager")
    public DataSourceTransactionManager clusterTransactionManager() {
        return new DataSourceTransactionManager(clusterDataSource());
    }

    @Bean(name = "clusterSqlSessionFactory")
    public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource clusterDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(clusterDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/mssmapper/**/*.xml"));
        return sessionFactory.getObject();
    }
}
@Configuration
//扫描 Mapper 接口并容器管理
@MapperScan(basePackages = {"com.example.transmission.msdata"}, sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfig {

    // 精确到 master 目录,以便跟其他数据源隔离
    static final String PACKAGE = "com.example.transmission.msdata";
    static final String MAPPER_LOCATION = "classpath:mapper/master/*.xml";

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

    @Value("${master.datasource.username}")
    private String user;

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

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

    @Primary
    @Bean(name = "masterDataSource")
    public DataSource masterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "masterTransactionManager")
    @Primary
    public DataSourceTransactionManager masterTransactionManager() {
        return new DataSourceTransactionManager(masterDataSource());
    }

    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(masterDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/msmapper/**/*.xml"));
        return sessionFactory.getObject();
    }
}

这两个类里需要修改得

basePackages = {"com.example.transmission.msdata"}
和masterSqlSessionFactory方法中.getResources("classpath:mapper/msmapper/**/*.xml"));

 

就是你项目中对应得项目路径  我得分别是

com.example.transmission.mssdata    com.example.transmission.msdata   mssdata路径下是sqlserver操作  msdata是mysql得操作     其实遇到得问题就是   sqlserver中得时间你需要提前转换成 年月日 时分秒得格式   不然存进mysql就尴尬了 这条数据你查是有的  但是时间却不一样 当你进行增量更新或者根据操作得时候就会有问题

 

最后是我得pom.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>transmission</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>transmission</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <druid>1.1.10</druid>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

项目实例 上传到资源了    需要可下载

发布了3 篇原创文章 · 获赞 2 · 访问量 2720
展开阅读全文

sprongboot配置双数问题

03-11

springboot 要配置一个mysql数据库一个sqlserver数据库 下面是我的配置 ``` spring: datasource: master: driver-class-name: com.mysql.jdbc.Driver jdbc-url: jdbc:mysql://***************************/gac?useUnicode=true&characterEncoding=UTF-8 username: **** password: **** other: driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver jdbc-url: jdbc:sqlserver://*********************** username: **** password: **** session: store-type: redis redis: host: **** port: **** ``` 主数据库配置 ``` @Primary @Bean(name = "masterDataSource") @ConfigurationProperties(prefix = "spring.datasource.master") public DataSource dataSource() { return DataSourceBuilder.create().build(); } @Primary @Bean(name = "masterSqlSessionFactory") public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); factoryBean.setTypeAliasesPackage("com.gac.entity"); factoryBean.setMapperLocations( new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml")); return factoryBean.getObject(); } @Primary @Bean(name = "masterTransactionManager") public DataSourceTransactionManager transactionManager(@Qualifier("masterDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Primary @Bean(name = "masterSqlSessionTemplate") public SqlSessionTemplate testSqlSessionTemplate( @Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } ``` 第二个数据库配置 ``` @Bean(name = "otherDataSource") @ConfigurationProperties(prefix = "spring.datasource.other") public DataSource dataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "otherTransactionManager") public DataSourceTransactionManager transactionManager(@Qualifier("otherDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "otherSqlSessionFactory") public SqlSessionFactory basicSqlSessionFactory(@Qualifier("otherDataSource") DataSource basicDataSource) throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(basicDataSource); factoryBean.setMapperLocations( new PathMatchingResourcePatternResolver().getResources("classpath:other/*.xml")); return factoryBean.getObject(); } @Bean(name = "otherSqlSessionTemplate") public SqlSessionTemplate testSqlSessionTemplate( @Qualifier("otherSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } ``` 启动类配置 ``` @Configuration @EnableTransactionManagement @SpringBootApplication(exclude={ DataSourceAutoConfiguration.class, //        HibernateJpaAutoConfiguration.class, //(如果使用Hibernate时,需要加)   DataSourceTransactionManagerAutoConfiguration.class, }) @Import({InitServiceConfiguration.class, InitConfiguration.class}) @ComponentScan("com.gac") public class adminApiApplication { public static void main(String[] args) { SpringApplication.run(adminApiApplication.class, args); } } ``` 报错 ``` Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: more than one 'primary' bean found among candidates: [masterDataSource, otherDataSource, dataSource] ``` 已经在主配置里面加了@Primary 然后在启动类里面也加了(exclude={ DataSourceAutoConfiguration.class, //        HibernateJpaAutoConfiguration.class, //(如果使用Hibernate时,需要加)   DataSourceTransactionManagerAutoConfiguration.class, }) 为什么还会报多数据源问题? 麻烦哪位大佬帮帮看一下问题 谢谢 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览