码迷,mamicode.com
首页 > 编程语言 > 详细

Spring boot 连接多数据源

时间:2019-05-27 09:15:36      阅读:35      评论:0      收藏:0      [点我收藏+]

标签:nec   import   manage   Fix   ret   eal   数据库   配置   icon   

1.application.yml中添加两个datasource

server:
  port: 8080
spring:
  application:
    name: king
  datasource:
    master:
      type: com.zaxxer.hikari.HikariDataSource
      jdbc-url: jdbc:mysql://localhost:3306/shengong?useUnicode=yes&characterEncoding=UTF-8&serverTimezone=UTC
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: arongking
      idle-timeout: 10000
      minimum-idle: 1
      maximum-pool-size: 10
      pool-name: master
      auto-commit: false
      connection-test-query: SELECT 1
    slave:
      type: com.zaxxer.hikari.HikariDataSource
      jdbc-url: jdbc:mysql://localhost:3306/king?useUnicode=yes&characterEncoding=UTF-8&serverTimezone=UTC
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: arongking
      idle-timeout: 10000
      minimum-idle: 1
      maximum-pool-size: 10
      pool-name: slave
      auto-commit: false
      connection-test-query: SELECT 1
2.手动初始化数据源masterDataSource
package cn.bj.king.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
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.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 org.springframework.core.io.support.