druid mysql 事务处理_Springboot+Mybatis+Druid 实现多数据源,与事务管理

本文介绍了如何在Springboot应用中配置和管理多个数据源,包括主数据源和辅助数据源,以及如何实现事务管理。通过示例展示了数据源的配置、数据库表结构、数据源配置类以及Mybatis的相关配置。同时,文章还提到了Druid的监控配置和使用注意事项,强调了在从库事务管理中需要显式指定事务管理器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.需求

一个主库的数据已经不能满足我们生产需求,需要额外的辅助库集成到项目里来获取所需的数据。或是将读写分开为两个库,完成自有的逻辑。

2.实现原理

如同在Springboot中配置一个数据源一样,我们需要一个主数据源,然后再用同样的方法配置另外一个数据源作为辅,两个数据源有各自独立的DataSourceTransactionManager与SqlSessionFactroy。

3.具体的实现

1) pom.xml

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

com.datasources

data

0.0.1-SNAPSHOT

jar

data

Demo project for Spring Boot

org.springframework.boot

spring-boot-starter-parent

1.5.4.RELEASE

UTF-8

UTF-8

1.8

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-test

test

org.mybatis.spring.boot

mybatis-spring-boot-starter

1.2.0

com.alibaba

druid

1.0.18

mysql

mysql-connector-java

org.springframework.boot

spring-boot-maven-plugin

2)application.properties

# 主数据源,默认的

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/test

spring.datasource.username=root

spring.datasource.password=root

spring.datasource.filters=stat,wall,log4j

# 更多数据源

custom.datasource.names=ds1,ds2

custom.datasource.ds1.driver-class-name=com.mysql.jdbc.Driver

custom.datasource.ds1.url=jdbc:mysql://localhost:3306/test1

custom.datasource.ds1.username=root

custom.datasource.ds1.password=root

custom.datasource.ds1.filters=stat,wall,log4j

3)数据库

数据库test ,表test

CREATE TABLE `test` (

`id` int(11) unsigned zerofill NOT NULL AUTO_INCREMENT,

`name` varchar(36) NOT NULL,

`age` int(2) NOT NULL,

`sex` varchar(2) DEFAULT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

数据库test1,表test

CREATE TABLE `test` (

`id` int(11) unsigned zerofill NOT NULL AUTO_INCREMENT,

`name` varchar(36) NOT NULL,

`age` int(2) NOT NULL,

`sex` varchar(2) DEFAULT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

两个库表没什么区别,只是单纯的分两个库用户测试。

4)配置数据源Master

package com.sorata.custom.datasources;

import com.alibaba.druid.pool.DruidDataSource;

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.context.annotation.Bean;

import org.springframework.context.annotation.Configuratio

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值