spring boot集成mysql多数据源

spring boot集成mysql多数据源,第1张

spring boot集成mysql多数据源

依赖


        org.springframework.boot
        spring-boot-starter-web
    
    
        org.springframework.boot
        spring-boot-starter-test
        test
    
    
        org.mybatis.spring.boot
        mybatis-spring-boot-starter
        1.3.1
    

    
        mysql
        mysql-connector-java
        ${jdbc-mysql-version}
        runtime
    

properties文件配置

spring.datasource.primary.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.primary.jdbc-url=jdbc:mysql://127.0.0.1:3316/open_tag?useUnicode=true&characterEncoding=utf8
spring.datasource.primary.username=dev
spring.datasource.primary.password=P0G5h#C!BhNM$Ki1


second 数据源配置
spring.datasource.secondary.jdbc-url=jdbc:mysql://127.0.0.1:3316/open_tag?useUnicode=true&characterEncoding=utf8
spring.datasource.secondary.username=bigdata
spring.datasource.secondary.password=zS^sNH4m%LjWQOMN
spring.datasource.secondary.driverClassName=com.mysql.cj.jdbc.Driver

数据源配置

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.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;


@Configuration
public class DataSourceConfig {
@Bean(name = "PrimaryDataSource")
@Qualifier("PrimaryDataSource")
@Primary
@ConfigurationProperties(prefix="spring.datasource.primary")
public DataSource primaryDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean(name = "SecondaryDataSource")
@Qualifier("SecondaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.secondary")
public DataSource secondaryDataSource() {
    return DataSourceBuilder.create().build();
}





@Bean(name="PrimaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate (
        @Qualifier("PrimaryDataSource")  DataSource dataSource ) {

    return new JdbcTemplate(dataSource);
}

@Bean(name="SecondaryJdbcTemplate")
public JdbcTemplate  secondaryJdbcTemplate(
        @Qualifier("SecondaryDataSource") DataSource dataSource) {

    return new JdbcTemplate(dataSource);
}

}

应用层

@Autowired
@Qualifier("PrimaryJdbcTemplate")
JdbcTemplate jdbcTemplate;

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5709180.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存