springboot配置mysql多数据源

本文介绍了如何在SpringBoot项目中配置多个数据源,利用JPA进行数据操作。通过在pom.xml添加依赖,设置application.yml文件实现数据源配置,包括业务库、收集数据库和推荐数据库的详细配置。此外,通过指定扫描的包,可以轻松区分不同数据源的使用。

1.pom.xml依赖

  <!--数据库-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

2.application.yml配置多数据源,这里使用springboot+jpa

server:
  port: 7803

spring:
 datasource1:
    driver-class-name: com.mysql.jdbc.Driver
    jdbc-url: jdbc:mysql://ip1:3306/demo1?useUnicode=true&characterEncoding=UTF-8&useSSL=false 
    username: username
    password: password
 datasource2:
    driver-class-name: com.mysql.jdbc.Driver
    jdbc-url: jdbc:mysql://ip2:3306/demo2?useUnicode=true&characterEncoding=UTF-8&useSSL=false 
    username: username
    password: pwd
  buss-datasource:
    driver-class-name: com.mysql.jdbc.Driver
    jdbc-url: jdbc:mysql://ip3:3306/tnoat_news_bz?useUnicode=true&characterEncoding=UTF-8&useSSL=false 
    username: username
    password: pwd
    jpa:
      database-platform: org.hibernate.dialect.MySQL5Dialect
      show-sql: false
      hibernate:
        ddl-auto: update



3.数据库统一配置文件

package com.tnaot.recommendreckon.base.config.datasource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;


/**
 * Author: hezishan
 * Date: 2018/5/25.
 * Description: 多数据源配置
 **/
@Configuration
public class DataSourceConfig {

    @Bean(name = "collectDataSource")
    @Qualifier("collectDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource1")
    public DataSource collectDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "recommendDataSource")
    @Qualifier("recommendDataSource")
    @ConfigurationProperties(prefix = "spring.datasource2")
    public DataSource recommendDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "bussDataSource")
    @Qualifier("bussDataSource")
    @ConfigurationProperties(prefix = "spring.datasource3")
    public DataSource bussDataSource() {
        return DataSourceBuilder.create().build();
    }

}

4.三个数据源的配置信息

业务库

package com.tnaot.recommendreckon.base.config.datasource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

/**
 * Author: hezishan
 * Date: 2018/5/25.
 * Description:
 **/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactoryBuss",
        transactionManagerRef="transactionManagerBuss",
        basePackages= { "com.tnaot.recommendreckon.core.bz.dao" })//设置dao(repo)所在位置
public class RepositoryBussConfig {
    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    @Qualifier("bussDataSource")
    private DataSource bussDataSource;

    @Bean(name = "entityManagerBuss")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryThird(builder).getObject().createEntityManager();
    }

    @Bean(name = "entityManagerFactoryBuss")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryThird(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(bussDataSource)
                .properties(getVendorProperties())
                .packages("com.tnaot.recommendreckon.core.bz.entity") //设置实体类所在位置
                .persistenceUnit("bussPersistenceUnit")
                .build();
    }

    private Map<String, Object> getVendorProperties() {
        return jpaProperties.getHibernateProperties(new HibernateSettings());
    }

    @Bean(name = "transactionManagerBuss")
    PlatformTransactionManager transactionManagerBuss(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryThird(builder).getObject());
    }
}

 

收集数据库配置

package com.tnaot.recommendreckon.base.config.datasource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

/**
 * Author: hezishan
 * Date: 2018/5/25.
 * Description: tnoat_data_collect 数据源配置
 **/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactoryCollect",
        transactionManagerRef="transactionManagerCollect",
        basePackages= { "com.tnaot.recommendreckon.core.collect.dao" })//设置dao(repo)所在位置
public class RepositoryCollectConfig {

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    @Qualifier("collectDataSource")
    private DataSource collectDataSource;

    @Bean(name = "entityManagerCollect")
    @Primary
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
    }

    @Bean(name = "entityManagerFactoryCollect")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(collectDataSource)
                .properties(getVendorProperties())
                .packages("com.tnaot.recommendreckon.core.collect.entity") //设置实体类所在位置
                .persistenceUnit("collectPersistenceUnit")
                .build();
    }

    private Map<String, Object> getVendorProperties() {
        return jpaProperties.getHibernateProperties(new HibernateSettings());
    }

    @Bean(name = "transactionManagerCollect")
    @Primary
    PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
    }

}

推荐数据库配置

package com.tnaot.recommendreckon.base.config.datasource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

/**
 * Author: hezishan
 * Date: 2018/5/25.
 * Description: tnaot_recommend 数据源配置
 **/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryRecommend",
        transactionManagerRef = "transactionManagerRecommend",
        basePackages = {"com.tnaot.recommendreckon.core.recommend.dao"})
public class RepositoryRecommendConfig {

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    @Qualifier("recommendDataSource")
    private DataSource recommendDataSource;

    @Bean(name = "entityManagerRecommend")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactorySecondary(builder).getObject().createEntityManager();
    }

    @Bean(name = "entityManagerFactoryRecommend")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(recommendDataSource)
                .properties(getVendorProperties())
                .packages("com.tnaot.recommendreckon.core.recommend.entity")
                .persistenceUnit("recommendPersistenceUnit")
                .build();
    }

    private Map<String, Object> getVendorProperties() {
        return jpaProperties.getHibernateProperties(new HibernateSettings());
    }

    @Bean(name = "transactionManagerRecommend")
    PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
    }

}

简单解释一下:通过分别配置上数据的一些信息来区分数据使用,同时指定了扫描的包,把数据库操作放在指定的包下就可以区分使用的数据源了,我的项目结构图为:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值