1、导入相应的jar包依赖

<!-- 集成mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency> <!-- 分布式事务管理 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jta-atomikos</artifactId>
</dependency>

2、配置多数据源

  2.1 在application.xml中配置多数据源的连接

spring:
datasource:
test1:
url: jdbc:mysql://localhost:3306/test
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
testQuery: select
test2:
url: jdbc:mysql://localhost:3306/test1
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
testQuery: select
mybatis:
mapper-locations: classpath:mapping/*.xml

  2.2 创建多数据库的连接信息配置类

@ConfigurationProperties(prefix="spring.datasource.test1")
@Primary
public class DB1Config { private String url; private String username; private String password; private String testQuery; public String getUrl() {
return url;
}

  ...添加get和set方法,如果多个数据源要配置多个
}

  2.3 创建多数据源的配置类,将不同的数据源交给jta的atomikos进行统一管理(多个数据源配置多个这样的文件)

@Configuration//注册到spring boot容器中
@MapperScan(basePackages="com.beifeng.hadoop.spring.boot.dao.jta.test1",sqlSessionFactoryRef="jtaTest1SqlSessionFactory")
public class JtaDataSource1Config { @Bean(name="jtaTest1DataSource")
@Primary//一个项目中只指定一个数据源为主数据源
public DataSource testDataSource(DB1Config db1Config){
MysqlXADataSource dataSource=new MysqlXADataSource();
dataSource.setUrl(db1Config.getUrl());
dataSource.setUser(db1Config.getUsername());
dataSource.setPassword(db1Config.getPassword());
dataSource.setPinGlobalTxToPhysicalConnection(true);
//将该数据源叫个atomikos进行统一管理
AtomikosDataSourceBean atomikosDataSource=new AtomikosDataSourceBean();
atomikosDataSource.setXaDataSource(dataSource);
atomikosDataSource.setUniqueResourceName("jtaTest1DataSource");
atomikosDataSource.setTestQuery(db1Config.getTestQuery());
return atomikosDataSource;
} @Bean(name="jtaTest1SqlSessionFactory")
@Primary
public SqlSessionFactory testSqlSessionFactory(@Qualifier("jtaTest1DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
} @Bean(name="jtaTest1SqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("jtaTest1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}

  2.4 在service中进行声明式事务配置

@Service
public class Test1JtaUserService { @Autowired//引入不同的数据源
private JtaUser1Dao jtaUser1Dao; @Autowired
private JtaUser2Dao jtaUser2Dao; @Transactional//声明式事务
public void insertJtaUser(String name,Integer age) {
jtaUser1Dao.insertUser(name, age);
jtaUser2Dao.insertUser(name, age);
int a=1/0;//如果出现异常,分布式事务会同时回滚
} }

  2.5 在启动类中声明多数据源的配置

@SpringBootApplication
@MapperScan("com.beifeng.hadoop.spring.boot.dao")//指定mybatis的dao扫包路径
@EnableConfigurationProperties(value={DB1Config.class,DB2Config.class})//指定多数据源的配置
public class App { public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

3 aop切面编程

@Aspect
@Component
public class WebLogAspect { private Logger logger=LoggerFactory.getLogger(WebLogAspect.class); private Long startTime; @Pointcut("execution(public * com.beifeng.hadoop.spring.boot.controller..*.*(..))")
public void webLog() { } @Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
logger.info("==============开始请求=============");
startTime=System.currentTimeMillis();
//接收到请求,记录请求内容
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest httpServletRequest=requestAttributes.getRequest();
logger.info("url: "+httpServletRequest.getRequestURL());
logger.info("http_method: "+httpServletRequest.getMethod());
logger.info("ip "+httpServletRequest.getRemoteAddr());
Enumeration<String> parameterNames = httpServletRequest.getParameterNames();
while (parameterNames.hasMoreElements()) {
String parameterName = (String) parameterNames.nextElement();
logger.info("parameter:{}->{}",parameterName,httpServletRequest.getParameter(parameterName));
}
} @AfterReturning(returning="ret",pointcut="webLog()")
public void doAfterReturning(Object ret) {
//处理完请求,返回内容
logger.info("响应结果:"+ret);
logger.info("==============开始结束,耗时"+(System.currentTimeMillis()-startTime)+"毫秒============="); }
}

springboot多数据库及分布式事务配置的更多相关文章

  1. 分布式事务、多数据源、分库分表中间件之spring boot基于Atomikos+XADataSource分布式事务配置(100%纯动态)

    本文描述spring boot基于Atomikos+DruidXADataSource分布式事务配置(100%纯动态),也就是增加.减少数据源只需要修改application.properties文件 ...

  2. 【转】PostgreSQL分布式事务配置

    XA是open group提出的分布式事务处理规范,JTA支持XA规范,JTA只规定了接口,有些应用容器提供实现,也有一些三方的开源实现可用,比如Atomikos. 如果PostgreSQL参与分布式 ...

  3. Springboot整合RocketMQ解决分布式事务

    直接上代码: 代码结构如下: 依次贴出相关类: DataSource1Config: package com.example.demo.config;import org.apache.ibatis. ...

  4. 测试web数据库的分布式事务atomikos 的三种数据源 SimpleDataSourceBean,AtomikosDataSourceBean,AtomikosNonXADataSourceBean

    这2天学习了atomikos事务控制框架,其中看到有3种数据源,分别是,SimpleDataSourceBean,AtomikosDataSourceBean,AtomikosNonXADataSou ...

  5. springboot学习笔记:10.springboot+atomikos+mysql+mybatis+druid+分布式事务

    前言 上一篇文章我们整合了springboot+druid+mybatis+mysql+多数据源: 本篇文章大家主要跟随你们涛兄在上一届基础上配置一下多数据源情况下的分布式事务: 首先,到底啥是分布式 ...

  6. 巨杉数据库SequoiaDB】巨杉Tech | SequoiaDB 分布式事务实现原理简介

    1 分布式事务背景 随着分布式数据库技术的发展越来越成熟,业内对于分布式数据库的要求也由曾经只用满足解决海量数据的存储和读取这类边缘业务向核心交易业务转变.分布式数据库如果要满足核心账务类交易需求,则 ...

  7. MySQL数据库分布式事务XA优缺点与改进方案

    1 MySQL 外部XA分析 1.1 作用分析 MySQL数据库外部XA可以用在分布式数据库代理层,实现对MySQL数据库的分布式事务支持,例如开源的代理工具:ameoba[4],网易的DDB,淘宝的 ...

  8. DTP模型之一:(XA协议之三)MySQL数据库分布式事务XA优缺点与改进方案

    1 MySQL 外部XA分析 1.1 作用分析 MySQL数据库外部XA可以用在分布式数据库代理层,实现对MySQL数据库的分布式事务支持,例如开源的代理工具:ameoba[4],网易的DDB,淘宝的 ...

  9. 数据库分布式事务XA规范介绍及Mysql底层实现机制

    1. 引言 分布式事务主要应用领域主要体现在数据库领域.微服务应用领域.微服务应用领域一般是柔性事务,不完全满足ACID特性,特别是I隔离性,比如说saga不满足隔离性,主要是通过根据分支事务执行成功 ...

随机推荐

  1. php Connection timed out after 30000 milliseconds

    function HttpRequest($url, $params, $method = 'GET', $header = array(), $bEncode = true){ $opts = ar ...

  2. python3.6:AttributeError: 'generator' object has no attribute 'next'

    环境:PyCharm+Anaconda python版本:3.6 协程测试: #!/usr/bin/env python # -*- coding:utf-8 -*- import time def ...

  3. 低版本vsphere部署高版本导出的OVF 报“硬件系列vmx-13不受支持“解决办法

    用文本编辑器之类的工具  打开ovf模板 然后下拉20多行左右 找到vmx-13这条报错内容 将13更改为数字较低的值 例如11,12

  4. How can I check the last time stats was run on Oracle without using OEM

    All of the following data dictionary tables have a LAST_ANALYZED column (replace * with USER/ALL/DBA ...

  5. matlab直接运行fig文件时报错

    Matlab里面所的程序都是以.m的脚本文件形式保存的,所有运行的都是m文件.所以,对于guide生成的GUI程序,打开的方式有两种: 一:打开.m文件,点击m文件上的运行按钮,会自动弹出figure ...

  6. PC-lint初体验

    当时用lint安装到VS2008上,找到两篇比较好的帖子: https://www.cnblogs.com/sanghg/p/4550829.html                     //这个 ...

  7. poj 2104 无修改主席树

    题目大意: 求序列的区间第k大 基本思路: 因为我根本就没有思路,知道这是主席树,我就去学了下,在b站上看了uestc的教学视频,然后看了一篇博客,博客http://www.cnblogs.com/E ...

  8. webpack第一节(4)

    每次修改了代码都需要重新手动打包,这样很麻烦,不符合webpack的初衷,我们查看webpack帮助看看有没有可以自动运行的方法 输入 webpack -help 可以发现有个 --watch方法 它 ...

  9. SSD的理解,为PyramidBox做准备

    目标检测主流方法有两大类 two-stage,以rcnn系列为主,采用建议框的方式对目标进行预测,过程首先要经过网络生成候选框,分类背景前景与进行第一次回归,之后再进行一次精细回归. 优点是准确率高, ...

  10. 关于Python实现Interface base64加解密方法

    ''' 以下Python Code运行环境为windows10, Python版本为3.5.3 涉及的库:base64,json,unittest ''' # coding=utf-8 # impor ...