原 spring boot Druid多

SpringBoot 多数据源配置

spring 多数据源配置一般有两种方案:

1、在spring项目启动的时候直接配置两个不同的数据源,不同的sessionFactory。在dao 层根据不同业务自行选择使用哪个数据源的session来操作。

2、配置多个不同的数据源,使用一个sessionFactory,在业务逻辑使用的时候自动切换到不同的数据源,有一个种是在拦截器里面根据不同的业务现切换到不同的datasource;有的会在业务层根据业务来自动切换。但这种方案在多线程并发的时候会出现一些问题,需要使用threadlocal等技术来实现多线程竞争切换数据源的问题。

【我就只讨论第一种方案】

spring多事务配置主要体现在db配置这块,配置不同的数据源和不同的session

1、pom.xml核心包:

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>${mybatis-spring-boot-starter.version}</version>
</dependency>
<!-- 阿里 连接池 -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid</artifactId>
	<version>${druid.version}</version>
</dependency>
<!--分布式事务支持 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-jta-atomikos</artifactId>
</dependency>

2、application.yml属性配置:

spring:
  datasource:
    one:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://192.168.1.206:3306/testOne?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false
      username: root
      password: 1234
    two:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://192.168.1.206:3306/testTwo?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false
      username: root
      password: 1234

3、接收数据源①:dataSource的Properties

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import lombok.Data;

@Data
@Component
@ConfigurationProperties(prefix = "spring.datasource.one")
public class OneDataSourceProperties {

    private String driverClassName;

    private String url;

    private String username;

    private String password;
}

4、设置①:dataSource

@Configuration
@MapperScan(basePackages = "com.xin.dream.one.dao", sqlSessionTemplateRef = "oneSqlSessionTemplate")
public class OneDatabaseConfig {
	@Autowired
	public OneDataSourceProperties oneDataSourceProperties;
	@Primary
	@Bean(name = "oneDataSource", destroyMethod = "close")
	public DataSource oneDataSource() {
		DruidXADataSource datasource = new DruidXADataSource();
    	BeanUtils.copyProperties(oneDataSourceProperties,datasource);
    	AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
        xaDataSource.setXaDataSource(datasource);
        xaDataSource.setUniqueResourceName("oneDataSource");
        return xaDataSource;
	}

	@Primary
	@Bean(name = "oneSqlSessionFactory")
	public SqlSessionFactory oneSqlSessionFactory(@Qualifier("oneDataSource") DataSource oneDataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(oneDataSource);
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		bean.setMapperLocations(resolver.getResources("classpath:com/xin/dream/one/mapper/*.xml"));
		return bean.getObject();
	}

	@Primary
	@Bean(name = "oneSqlSessionTemplate")
	public SqlSessionTemplate oneSqlSessionTemplate(
			@Qualifier("oneSqlSessionFactory") SqlSessionFactory oneSqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(oneSqlSessionFactory);
	}
}

5、第②数据源和①的步骤一样,改掉别名,和去掉@Primary,就好了。这个时候事务已经是被管理的了

源码地址:https://gitee.com/bianxin.com/SpringBootAtomikos

在开发中遇见问题

配置文件:

spring:
  jta:
    atomikos:
      datasource:
        oneData:
          max-pool-size: 25
          min-pool-size: 3
          max-lifetime: 20000
          xa-data-source-class-name: com.alibaba.druid.pool.xa.DruidXADataSource
          borrow-connection-timeout: 10000
          unique-resource-name: fs
          xa-properties:
            password: 1234
            username: root
            url: jdbc:mysql://192.168.1.206:3306/testOne?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false
        twoData:
          max-pool-size: 25
          min-pool-size: 3
          max-lifetime: 20000
          xa-data-source-class-name: com.alibaba.druid.pool.xa.DruidXADataSource
          unique-resource-name: party
          borrow-connection-timeout: 10000 
          xa-properties:
            password: 1234
            username: root
            url: jdbc:mysql://192.168.1.206:3306/testOne?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false
    enabled: true

为了节减代码量dataSource配置文件为:

@Configuration
@MapperScan(basePackages = "com.xin.dream.one.dao", sqlSessionTemplateRef = "oneSqlSessionTemplate")
public class OneDatabaseConfig {
	
	@Primary
	@Bean(name = "oneDataSource", destroyMethod = "close")
	@ConfigurationProperties(prefix = "spring.jta.atomikos.datasource.oneData")
	public DataSource oneDataSource() {
		return new AtomikosDataSourceBean();
	}

	@Primary
	@Bean(name = "oneSqlSessionFactory")
	public SqlSessionFactory oneSqlSessionFactory(@Qualifier("oneDataSource") DataSource oneDataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(oneDataSource);
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		bean.setMapperLocations(resolver.getResources("classpath:com/xin/dream/one/mapper/*.xml"));
		return bean.getObject();
	}

	@Primary
	@Bean(name = "oneSqlSessionTemplate")
	public SqlSessionTemplate oneSqlSessionTemplate(
			@Qualifier("oneSqlSessionFactory") SqlSessionFactory oneSqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(oneSqlSessionFactory);
	}

}

当有多个数据源的时候报错:

Caused by: com.atomikos.jdbc.AtomikosSQLException: Cannot initialize AtomikosDataSourceBean
	at com.atomikos.jdbc.AtomikosSQLException.throwAtomikosSQLException(AtomikosSQLException.java:46) ~[transactions-jdbc-3.9.3.jar:na]
	at com.atomikos.jdbc.AbstractDataSourceBean.init(AbstractDataSourceBean.java:306) ~[transactions-jdbc-3.9.3.jar:na]
	at org.springframework.boot.jta.atomikos.AtomikosDataSourceBean.afterPropertiesSet(AtomikosDataSourceBean.java:49) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
	... 80 common frames omitted
Caused by: java.lang.IllegalArgumentException: argument type mismatch
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_131]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_131]
	at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_131]
	at com.atomikos.beans.PropertyUtils.setDirectProperty(PropertyUtils.java:205) ~[atomikos-util-3.9.3.jar:na]
	at com.atomikos.beans.PropertyUtils.setProperty(PropertyUtils.java:110) ~[atomikos-util-3.9.3.jar:na]
	at com.atomikos.beans.PropertyUtils.setProperties(PropertyUtils.java:186) ~[atomikos-util-3.9.3.jar:na]
	at com.atomikos.jdbc.AtomikosDataSourceBean.doInit(AtomikosDataSourceBean.java:196) ~[transactions-jdbc-3.9.3.jar:na]
	at com.atomikos.jdbc.AbstractDataSourceBean.init(AbstractDataSourceBean.java:296) ~[transactions-jdbc-3.9.3.jar:na]
	... 83 common frames omitted

我跟踪了源码,水平有限,暂时还没弄懂原因,想直接new AtomikosDataSourceBean()或者简单的赋值,怎么弄?望朋友们指点下?

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏极客编程

用Visual Studio Code和CLion进行EOS开发

每一个开发人员都需要一个良好的IDE,EOS开发也是一样,为项目开发过程构建一个良好的IDE环境是第一步。这就是为什么我们要写这个如何使用VS Code或者CL...

28220
来自专栏IT进修之路

原 荐 Spring Boot 多库分布式事

28770
来自专栏蓝天

Hive 0.12.0安装指南

本文的安装参照了官方的文档:GettingStarted,将Hive 0.12.0安装在Hadoop 2.4.0上。本文将Hive配置成Server模式,并...

7330
来自专栏Kubernetes

Kubernetes Nginx Ingress Controller源码分析之创建篇

main controllers/nginx/pkg/cmd/controller/main.go:29 func main() { // start a ...

91970
来自专栏owent

GCC 7和LLVM+Clang+libc++abi 4.0的构建脚本

之前的版本发完,有空来更新一下之前的gcc和llvm+clang工具链的编译脚本了。其实GCC 7是才release没多久但是llvm 4.0发布其实有一段时间...

9410
来自专栏SpringSpace.cn

在 ubuntu 12.10 中安装 opensips 1.8.2

解压软件包: tar -zxvf opensips-1.8.2_src.tar.gz

25020
来自专栏个人分享

spark单机模式简单搭建

待安装列表 hadoop hive scala spark 一.环境变量配置: ~/.bash_profile PATH=$PATH:$HOME/bin

61910
来自专栏IT进修之路

原 荐 SpringBoot整合mybati

20740
来自专栏bboysoul

linux 格式化硬盘

fdisk /dev/sda 输入o建立dos分区表 输入n建立一个新的分区 输入p建立一个主分区,或者输入e建立一个逻辑分区 之后输入分区号码mbr只...

25550
来自专栏向治洪

ActivityManagerService启动过程分析

之前讲Android的View的绘制原理和流程的时候,讲到过在Android调用setContentView之后,Android调用了一个prepreTravl...

27380

扫码关注云+社区

领取腾讯云代金券