springboot-多数据源(基于JdbcTemplate的方式)

引入依赖pom.xml:

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
        <relativePath/>
        <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
    </dependencies>

yml的配置文件:

##端口号
server:
  port: 9999

  ##数据库url
spring:
  jpa:
   database-platform: org.hibernate.dialect.MySQL5Dialect
  datasource:
   multiDataSource0:
    url: jdbc:mysql://localhost:3306/mutil_datasource0?serverTimezone=GMT%2B8&characterEncoding=UTF-8&useSSL=false&rewriteBatchedStatements=true&zeroDateTimeBehavior=convertToNull
  ##数据库用户名
    username: root
  ##数据库密码
    password: root
  ##数据库驱动
    driver-class-name: com.mysql.jdbc.Driver
  ##数据库url
   multiDataSource1:
    url: jdbc:mysql://localhost:3306/multi_datasource1?serverTimezone=GMT%2B8&characterEncoding=UTF-8&useSSL=false&rewriteBatchedStatements=true&zeroDateTimeBehavior=convertToNull
  ##数据库用户名
    username: root
  ##数据库密码
    password: root
  ##数据库驱动
    driver-class-name: com.mysql.jdbc.Driver

设置JdbcTemplate的配置:JdbcTemplateConfig.java

package cn.caraliu.config;

import com.atomikos.icatch.jta.UserTransactionImp;
import com.atomikos.icatch.jta.UserTransactionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
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 org.springframework.transaction.jta.JtaTransactionManager;

import javax.sql.DataSource;
import javax.transaction.UserTransaction;

@Configuration
public class JdbcTemplateConfig {

    @Bean(name = "dataSource0") // 引入要注入两个同种类型的bean,所以要注入不同的名字来区分
    @Primary //优先考虑注入这个数据源,当没有显示指定的时候
    @ConfigurationProperties(prefix="spring.datasource.multiDataSource0")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

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

    @Primary
    @Bean
    JdbcTemplate jdbcTemplate0(@Qualifier("dataSource0") DataSource dataSource0) {
        return new JdbcTemplate(dataSource0);
    }

    @Bean
    JdbcTemplate jdbcTemplate1(@Qualifier("dataSource1") DataSource dataSource1) {
        return new JdbcTemplate(dataSource1);
    }

}

控制层:

/**
 * @author chenjianhui on 2020/04/02
 */
@Controller
@RequestMapping(value = "/v1")
public class MultiDatasourceController {

    @Autowired
    private MultiDatasouceService multiDatasouceService;
    @RequestMapping(value = "/mutilDatasource",method = RequestMethod.GET)
    public ResponseEntity<?> mutilDatasource(){
        multiDatasouceService.executeDatasource();
        return new ResponseEntity<Object>(null, HttpStatus.OK);
    }
}

服务层:

/**
 * @author chenjianhui on 2020/04/02
 */
public interface MultiDatasouceService {

    void executeDatasource();
}

package cn.caraliu.service.impl;

import cn.caraliu.service.MultiDatasouceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * @author chenjianhui on 2020/04/02
 */
@Service
public class MultiDatasouceServiceImpl implements MultiDatasouceService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Qualifier("jdbcTemplate0") // 注入的时候要指定名字,不然会注入优先的那个bean
    @Autowired
    private JdbcTemplate jdbcTemplate0;
    @Qualifier("jdbcTemplate1")
    @Autowired
    private JdbcTemplate jdbcTemplate1;

    @Override
    public void executeDatasource() {
        jdbcTemplate1.update("INSERT INTO `multi_datasource1`.`black_user` (`app_type`, `user_pk`) VALUES ('1', '3')");
        jdbcTemplate0.update("INSERT INTO `mutil_datasource0`.`black_user` (`app_type`, `user_pk`) VALUES ('1', '3')");
    }
}

然后请求相应的接口,发现两个数据库的两张表都插入了一条数据。

上述的配置首先是像容器中注入了两个不同的数据源,当一个操作数据库的实体类,引入不同的数据源的时候,就可以操作不同的数据库,比如上述中的JdbcTemplate,不同的数据源,那么操作的数据库就不同。其他的也是类似,比如jpa的设置,可以通过所处的包位置不同,设置不同的数据库。就是将实体类放在不同的配置包里,相应的包里配置了一个相应的数据源,那么就可以操作该数据源对应的那个数据库里面的表。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值