SpringBoot + JPA 配置双数据源

一、首先配置application.yml 

server:
  port: 8081
  servlet:
    context-path: /

  #是否开启压缩,默认false
  compression:
    enabled: true
    #执行压缩的阀值,默认2048,单位:字节B
    min-response-size: 2048
    #指定要压缩的MIME type,多个以逗号分隔,[text/html, text/xml, text/plain, text/css, text/javascript, application/javascript, application/json, application/xml]
    mime-types: application/json,application/xml,text/html,text/xml,text/plain

spring:
  application:
    name: chint-kml-api
  datasource:
    ds1:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://xx:3306/chiticbank?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=UTC
      username: xx
      password: xx@123
    ds2:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://xx:3306/smartpower?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai
      username: xx
      password: xx@123456
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      minimum-idle: 5
      maximum-pool-size: 15
      auto-commit: true
      idle-timeout: 30000
      pool-name: DatebookHikariCP
      max-lifetime: 1800000
      connection-timeout: 30000
      connection-test-query: SELECT 1
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    database: mysql

二、使用配置类读取application.yml配置的两个数据源,并将其注入到Spring的IOC容器中

package com.chint.kml.api.config;

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;
 
 
@Configuration
public class DataSourceConfig {
 
    @Bean(name = "ds1DataSource")
    @Qualifier("ds1DataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.ds1")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
 
    @Bean(name = "ds2DataSource")
    @Qualifier("ds2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.ds2")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
 
}

三、配置两个数据源

 (一):数据源1

package com.chint.kml.api.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
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;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryDs1",
        transactionManagerRef = "transactionManagerDs1",
        basePackages = {"com.chint.kml.api.repository.rep1"})
public class Ds1Config {

    @Autowired
    @Qualifier("ds1DataSource")
    private DataSource ds1Datasource;

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    private HibernateProperties hibernateProperties;

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

    @Bean(name = "entityManagerDs1")
    @Primary
    public EntityManager entityManagerDs1(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryDs1(builder).getObject().createEntityManager();
    }

    /**
     * 设置实体类所在位置
     */
    @Bean(name = "entityManagerFactoryDs1")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryDs1(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(ds1Datasource)
                .packages("com.chint.kml.api.repository.rep1")
                .persistenceUnit("ds1PersistenceUnit")
                .properties(getVendorProperties())
                .build();
    }

    @Bean(name = "transactionManagerDs1")
    @Primary
    public PlatformTransactionManager transactionManagerDs1(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryDs1(builder).getObject());
    }

}

 (二):数据源2

package com.chint.kml.api.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
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;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryDs2",
        transactionManagerRef = "transactionManagerDs2",
        basePackages = {"com.chint.kml.api.repository.rep2"})
public class Ds2Config {

    @Autowired
    @Qualifier("ds2DataSource")
    private DataSource ds2Datasource;

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    private HibernateProperties hibernateProperties;

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

    @Bean(name = "entityManagerDs2")
    public EntityManager entityManagerDs2(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryDs2(builder).getObject().createEntityManager();
    }

    /**
     * 设置实体类所在位置
     */
    @Bean(name = "entityManagerFactoryDs2")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryDs2(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(ds2Datasource)
                .packages("com.chint.kml.api.repository.rep2")
                .persistenceUnit("ds2PersistenceUnit")
                .properties(getVendorProperties())
                .build();
    }

    @Bean(name = "transactionManagerDs2")
    public PlatformTransactionManager transactionManagerDs2(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryDs2(builder).getObject());
    }

}

四、启动类主函数入口

SpringBoot启动类需关闭注解 ,程序启动加载的仓库(@EnableJpaRepositories),因为在数据源配置类中已经开启了
@SpringBootApplication
//@EnableJpaRepositories
@ComponentScan(CoreConstants.BASE_PACKAGE)
public class ChintKmlApiServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(ChintKmlApiServiceApplication.class, args);
        LoadPoints loadPoints = SpringUtils.getBean(LoadPoints.class);
        loadPoints.loadPoints();
    }

}

注意:springboot版本

2.3.8.RELEASE

 

posted @ 2021-06-21 15:13  高木子  阅读(1024)  评论(0编辑  收藏  举报