springboot 多数据源

来源:互联网 发布:淘宝联盟分享赚互刷 编辑:程序博客网 时间:2024/05/17 21:40

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: 3031demo:  datasource:    url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=true    user: root    password: 123456    driverClassName: com.mysql.jdbc.Driverarticle:  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
原创粉丝点击