springboot 多数据源

springboot 多数据源

一般而言,互联网公司的项目都是多数据源连接,当然springboot肯定也会支持多数据源喽。
本地有两个数据库 分别是demo,里面有表user

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(128) NOT NULL,
  `age` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

数据库xiaoyun 有article表

CREATE TABLE `article` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(45) DEFAULT NULL,
  `contentLeft` varchar(1024) NOT NULL,
  `authorId` int(11) NOT NULL,
  `createTime` datetime NOT NULL,
  `contentRight` varchar(1024) NOT NULL,
  `contentHtml` varchar(1024) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

数据库配置 yml文件

server:
  port: 3031

demo:
  datasource:
    url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=true
    user: root
    password: 123456
    driverClassName: com.mysql.jdbc.Driver

article:
  datasource:
    url: jdbc:mysql://localhost:3306/xiaoyun?useUnicode=true&characterEncoding=utf8&useSSL=true
    user: root
    password: 123456
    driverClassName: com.mysql.jdbc.Driver

xiaoyun 库的 数据库配置代码

package smaug.api.dataConfig;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by naonao on 17/4/23.
 */
@Configuration
@MapperScan(basePackages = ArticleConfig.PACKAGE, sqlSessionFactoryRef = "articleSqlSessionFactory")
public class ArticleConfig {
    static final String PACKAGE = "smaug.api.mapper.article";
    static final String MAPPER_LOCATION = "classpath:mybatis/article/*.xml";

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

    @Value("${article.datasource.user}")
    private String userName;

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

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

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

    @Bean(name = "articleTransactionManager")
    public DataSourceTransactionManager articleTransactionManager() {
        return new DataSourceTransactionManager(articleDataSource());
    }

    @Bean(name = "articleSqlSessionFactory")
    public SqlSessionFactory articleTransactionManager(@Qualifier("articleDataSource") DataSource articleDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(articleDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(ArticleConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}

demo数据库的配置

    static final String PACKAGE = "smaug.api.mapper.demo";
    static final String MAPPER_LOCATION = "classpath:mybatis/demo/*.xml";

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

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

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

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

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

    @Bean(name = "demoTransactionManager")
    //@Primary
    public DataSourceTransactionManager demoTransactionManager() {
        return new DataSourceTransactionManager(demoDataSource());
    }

    @Bean(name = "demoSqlSessionFactory")
    //@Primary
    public SqlSessionFactory demoSqlSessionFactory(@Qualifier("demoDataSource") DataSource demoDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(demoDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(DemoConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

既然是两个datasource bean 就一定会有冲突,果不其然, 跑起来的时候会报错

Field demoArticleEntityMapper in smaug.api.services.BaseService required a single bean, but 2 were found:
    - articleDataSource: defined by method 'articleDataSource' in class path resource [smaug/api/dataConfig/ArticleConfig.class]
    - demoDataSource: defined by method 'demoDataSource' in class path resource [smaug/api/dataConfig/DemoConfig.class]


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

所以demo里注释的注解 @Primary 必须要有

然后此时运行程序,即可以正常运行哦

详见代码demo

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值