說明
- 隨著應用用戶數(shù)量的增加,相應的并發(fā)請求的數(shù)量也會跟著不斷增加容燕,慢慢地梁呈,單個數(shù)據(jù)庫已經(jīng)沒有辦法滿足我們頻繁的數(shù)據(jù)庫操作請求了。
- 在某些場景下蘸秘,我們可能會需要配置多個數(shù)據(jù)源官卡,使用多個數(shù)據(jù)源(例如實現(xiàn)數(shù)據(jù)庫的讀寫分離)來緩解系統(tǒng)的壓力等,同樣的醋虏,SpringBoot官方提供了相應的實現(xiàn)來幫助開發(fā)者們配置多數(shù)據(jù)源寻咒,據(jù)我目前所了解到的,一般分為兩種方式靜態(tài)與動態(tài)(分包和AOP)颈嚼。本文使用的是靜態(tài)的方式仔涩。
- 因為我們控制是多數(shù)據(jù)源DataSource,而并不用關(guān)心到底是用哪種方式去使用粘舟,比如源生JDBC熔脂、MyBatis、Hibernate等上層的使用方法都是一樣的柑肴。所以本文以本人常用的MyBatis-Plus操作數(shù)據(jù)源為例霞揉。
- 本文中數(shù)據(jù)庫用的是mysql5.7。完整代碼地址在結(jié)尾N铩适秩!
- 靜態(tài)方式方式說白了绊序,其實就是根據(jù)不同的包路徑定義多個數(shù)據(jù)源,想用哪個用哪個唄秽荞。
第一步骤公,分別創(chuàng)建兩個數(shù)據(jù)庫db1,db2扬跋,sql如下
db1
CREATE DATABASE db1;
use db1;
CREATE TABLE user
(
id INT NOT NULL COMMENT '主鍵ID',
name VARCHAR(50) NULL DEFAULT NULL COMMENT '姓名',
age INT NULL DEFAULT NULL COMMENT '年齡',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '郵箱',
PRIMARY KEY (id)
)CHARSET=utf8 ENGINE=InnoDB COMMENT '用戶表';
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
select * from user;
db2
CREATE DATABASE db2;
use db2;
CREATE TABLE task
(
id INT NOT NULL COMMENT '主鍵ID',
name VARCHAR(50) NULL DEFAULT NULL COMMENT '姓名',
age INT NULL DEFAULT NULL COMMENT '年齡',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '郵箱',
PRIMARY KEY (id)
)CHARSET=utf8 ENGINE=InnoDB COMMENT '任務表';
INSERT INTO task (id, name, age, email) VALUES
(1, '李白', 18, 'test1@baomidou.com'),
(2, '露娜', 20, 'test2@baomidou.com'),
(3, '韓信', 28, 'test3@baomidou.com'),
(4, '橘右京', 21, 'test4@baomidou.com'),
(5, '百里玄刺', 24, 'test5@baomidou.com');
select * from task;
第二步阶捆,在pom.xml加入依賴,如下
<!-- MySQL驅(qū)動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- mybatisPlus 核心庫 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
第三步钦听,在application.yml配置多數(shù)據(jù)源洒试,mybatis-plus相關(guān)配置
spring:
datasource:
db1:
jdbc-url: jdbc:mysql://xxx:3306/db1?useUnicode=true&characterEncoding=utf-8
username: xxx
password: xxx
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
最小空閑連接數(shù)量
minimum-idle: 5
連接池最大連接數(shù),默認是10
maximum-pool-size: 15
連接池名稱
pool-name: MyHikariCPOfMaster
此屬性控制池中連接的最長生命周期朴上,值0表示無限生命周期垒棋,默認1800000即30分鐘
max-lifetime: 1800000
數(shù)據(jù)庫連接超時時間,默認30秒,即30000
connection-timeout: 20000
空閑連接存活最大時間痪宰,默認600000(10分鐘)
idle-timeout: 180000
此屬性控制從池返回的連接的默認自動提交行為,默認值:true
auto-commit: true
connection-test-query: SELECT 1
db2:
jdbc-url: jdbc:mysql://xxx:3306/db2?useUnicode=true&characterEncoding=utf-8
username: xxx
password: xxx
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
最小空閑連接數(shù)量
minimum-idle: 5
連接池最大連接數(shù)叼架,默認是10
maximum-pool-size: 15
連接池名稱
pool-name: MyHikariCPOfMaster
此屬性控制池中連接的最長生命周期,值0表示無限生命周期衣撬,默認1800000即30分鐘
max-lifetime: 1800000
數(shù)據(jù)庫連接超時時間,默認30秒乖订,即30000
connection-timeout: 20000
空閑連接存活最大時間,默認600000(10分鐘)
idle-timeout: 180000
此屬性控制從池返回的連接的默認自動提交行為,默認值:true
auto-commit: true
connection-test-query: SELECT 1
application:
name: staticmultipledatasources-demo-server
# mybatis-plus相關(guān)配置
mybatis-plus:
configuration:
#不開啟二級緩存
cache-enabled: false
# 是否開啟自動駝峰命名規(guī)則映射:從數(shù)據(jù)庫列名到Java屬性駝峰命名的類似映射
map-underscore-to-camel-case: true
# 如果查詢結(jié)果中包含空值的列淮韭,則 MyBatis 在映射的時候,不會映射這個字段
call-setters-on-nulls: true
# 這個配置會將執(zhí)行的sql打印出來贴届,在開發(fā)或測試的時候可以用
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
server:
port: 8092
第四步靠粪,將spring boot自帶的DataSourceAutoConfiguration禁掉,因為它會讀取application.yml文件的spring.datasource.*屬性并自動配置單數(shù)據(jù)源毫蚓。在@SpringBootApplication注解中添加exclude屬性即可占键,如下
StaticMultipleDataSourcesApplication
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class StaticMultipleDataSourcesApplication {
public static void main(String[] args) {
SpringApplication.run(StaticMultipleDataSourcesApplication.class, args);
}
}
第五步,創(chuàng)建配置文件DB1DataSourceConfig元潘,DB2DataSourceConfig畔乙,MybatisPlusConfig,如下
DB1DataSourceConfig
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
/**
* @Description:
* @Author: jinhaoxun
* @Date: 2020/5/9 8:27 下午
* @Version: 1.0.0
*/
@Configuration
@MapperScan(basePackages = {"com.luoyu.staticmultipledatasources.mapper.db1"}, sqlSessionTemplateRef ="db1SqlSessionTemplate")
public class DB1DataSourceConfig {
/**
* 創(chuàng)建數(shù)據(jù)源
* @return
*/
@Bean(name = "db1DataSource")
@ConfigurationProperties(prefix="spring.datasource.db1")
@Primary
public DataSource getDB1DataSource() {
return DataSourceBuilder.create().build();
}
/**
* 創(chuàng)建SessionFactory
* @param db1DataSource
* @return
* @throws Exception
*/
@Bean(name = "db1SqlSessionFactory")
@Primary
public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource db1DataSource, @Qualifier("mybatisplusConfiguration") org.apache.ibatis.session.Configuration configuration) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(db1DataSource);
// 使mybatis-plus配置生效翩概,加載順序問題
bean.setConfiguration(configuration);
// mapper的xml形式文件位置必須要配置牲距,不然將報錯:no statement (這種錯誤也可能是mapper的xml中,namespace與項目的路徑不一致導致)
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/luoyu/staticmultipledatasources/mapper/db1/xml/*.xml"));
bean.setTypeAliasesPackage("com.luoyu.staticmultipledatasources.entity");
return bean.getObject();
}
/**
* 創(chuàng)建事務管理器
* @param db1DataSource
* @return
*/
@Bean("db1TransactionManger")
@Primary
public DataSourceTransactionManager db1TransactionManger(@Qualifier("db1DataSource") DataSource db1DataSource){
return new DataSourceTransactionManager(db1DataSource);
}
/**
* 創(chuàng)建SqlSessionTemplate
* @param db1SqlSessionFactory
* @return
*/
@Bean(name = "db1SqlSessionTemplate")
@Primary
public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory db1SqlSessionFactory){
return new SqlSessionTemplate(db1SqlSessionFactory);
}
}
DB2DataSourceConfig
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
/**
* @Description:
* @Author: jinhaoxun
* @Date: 2020/5/9 8:26 下午
* @Version: 1.0.0
*/
@Configuration
@MapperScan(basePackages = "com.luoyu.staticmultipledatasources.mapper.db2",sqlSessionTemplateRef ="db2SqlSessionTemplate")
public class DB2DataSourceConfig {
/**
* 創(chuàng)建數(shù)據(jù)源
* @return
*/
@Bean(name = "db2DataSource")
@ConfigurationProperties(prefix="spring.datasource.db2")
@Primary
public DataSource getDB2DataSource() {
return DataSourceBuilder.create().build();
}
/**
* 創(chuàng)建SessionFactory
* @param db2DataSource
* @return
* @throws Exception
*/
@Bean(name = "db2SqlSessionFactory")
@Primary
public SqlSessionFactory db2SqlSessionFactory(@Qualifier("db2DataSource") DataSource db2DataSource, @Qualifier("mybatisplusConfiguration") org.apache.ibatis.session.Configuration configuration) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(db2DataSource);
// 使mybatis-plus配置生效钥庇,加載順序問題
bean.setConfiguration(configuration);
// mapper的xml形式文件位置必須要配置牍鞠,不然將報錯:no statement (這種錯誤也可能是mapper的xml中,namespace與項目的路徑不一致導致)
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/luoyu/staticmultipledatasources/mapper/db2/xml/*.xml"));
bean.setTypeAliasesPackage("com.luoyu.staticmultipledatasources.entity");
return bean.getObject();
}
/**
* 創(chuàng)建事務管理器
* @param db2DataSource
* @return
*/
@Bean("db2TransactionManger")
@Primary
public DataSourceTransactionManager db2TransactionManger(@Qualifier("db2DataSource") DataSource db2DataSource){
return new DataSourceTransactionManager(db2DataSource);
}
/**
* 創(chuàng)建SqlSessionTemplate
* @param db2SqlSessionFactory
* @return
*/
@Bean(name = "db2SqlSessionTemplate")
@Primary
public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory db2SqlSessionFactory){
return new SqlSessionTemplate(db2SqlSessionFactory);
}
}
MybatisPlusConfig
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.annotation.Order;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @Description: MybatisPlus配置類
* @Author: jinhaoxun
* @Date: 2020/2/13 上午11:34
* @Version: 1.0.0
*/
@EnableTransactionManagement
@Configuration
@Order(-1)
public class MybatisPlusConfig {
/**
* 使application.properties配置生效评姨,如果不主動配置难述,由于@Order配置順序不同,將導致配置不能及時生效,多數(shù)據(jù)源配置駝峰法生效
* @return 數(shù)據(jù)源
*/
@Bean("mybatisplusConfiguration")
@ConfigurationProperties(prefix = "mybatis-plus.configuration")
@Scope("prototype")
public org.apache.ibatis.session.Configuration globalConfiguration() {
return new org.apache.ibatis.session.Configuration();
}
/**
* mybatis-plus SQL執(zhí)行效率插件【生產(chǎn)環(huán)境可以關(guān)閉】胁后,設置 dev test 環(huán)境開啟
*/
// @Bean
// @Profile({"dev", "qa"})
// public PerformanceInterceptor performanceInterceptor() {
// PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
// performanceInterceptor.setMaxTime(1000);
// performanceInterceptor.setFormat(true);
// return performanceInterceptor;
// }
/**
* 分頁插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 設置請求的頁面大于最大頁后操作店读, true調(diào)回到首頁,false 繼續(xù)請求 默認false
paginationInterceptor.setOverflow(false);
// 設置最大單頁限制數(shù)量攀芯,默認 500 條屯断,-1 不受限制
paginationInterceptor.setLimit(500);
// 開啟 count 的 join 優(yōu)化,只針對部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
}
第六步,創(chuàng)建Task敲才,User裹纳,如下
Task
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* <p>
*
* </p>
*
* @author jinhaoxun
* @since 2020-02-13
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class Task implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主鍵id
*/
private Integer id;
/**
* 姓名
*/
private String name;
/**
* 年齡
*/
private Integer age;
/**
* 郵箱
*/
private String email;
}
User
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author jinhaoxun
* @since 2020-02-13
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主鍵id
*/
private Integer id;
/**
* 姓名
*/
private String name;
/**
* 年齡
*/
private Integer age;
/**
* 郵箱
*/
private String email;
}
第七步,分別創(chuàng)建UserMapper紧武,UserMapper.xml剃氧,TaskMapper,TaskMapper.xml阻星,放在不同的包下朋鞍,如下
UserMapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.luoyu.staticmultipledatasources.entity.User;
import org.apache.ibatis.annotations.Param;
/**
* <p>
* Mapper 接口
* </p>
*
* @author jinhaoxun
* @since 2020-02-13
*/
public interface UserMapper extends BaseMapper<User> {
/**
* @Author: jinhaoxun
* @Description:
* @param id id
* @Date: 2020/2/13 下午12:06
* @Throws:
*/
User selectById(Integer id);
/**
* @Author: jinhaoxun
* @Description:
* @param id id
* @param name 姓名
* @Date: 2020/2/13 下午12:06
* @Return: int
* @Throws:
*/
int updateName(@Param("id") int id, @Param("name") String name);
}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.luoyu.staticmultipledatasources.mapper.db1.UserMapper">
<select id="selectById" parameterType="java.lang.Integer" resultType="com.luoyu.staticmultipledatasources.entity.User">
select * from user where id = #{id};
</select>
<update id="updateName">
update user set name = #{name} where id = #{id};
</update>
</mapper>
TaskMapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.luoyu.staticmultipledatasources.entity.Task;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* <p>
* Mapper 接口
* </p>
*
* @author jinhaoxun
* @since 2020-02-13
*/
@Mapper
public interface TaskMapper extends BaseMapper<Task> {
/**
* @Author: jinhaoxun
* @Description:
* @param id id
* @Date: 2020/2/13 下午12:06
* @Throws:
*/
Task selectById(Integer id);
/**
* @Author: jinhaoxun
* @Description:
* @param id id
* @param name 姓名
* @Date: 2020/2/13 下午12:06
* @Return: int
* @Throws:
*/
int updateName(@Param("id") int id, @Param("name") String name);
}
TaskMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.luoyu.staticmultipledatasources.mapper.db2.TaskMapper">
<select id="selectById" parameterType="java.lang.Integer" resultType="com.luoyu.staticmultipledatasources.entity.Task">
select * from task where id = #{id};
</select>
<update id="updateName">
update task set name = #{name} where id = #{id};
</update>
</mapper>
路徑如下:
image.png
第八步,創(chuàng)建IUserService妥箕,TaskServiceImpl滥酥,ITaskService,TaskServiceImpl畦幢,如下
IUserService
import com.baomidou.mybatisplus.extension.service.IService;
import com.luoyu.staticmultipledatasources.entity.User;
/**
* <p>
* 服務類
* </p>
*
* @author jinhaoxun
* @since 2020-02-13
*/
public interface IUserService extends IService<User> {
/**
* @Author: jinhaoxun
* @Description:
* @param id id
* @Date: 2020/2/13 下午12:06
* @Throws:
*/
User selectById(Integer id);
/**
* @Author: jinhaoxun
* @Description:
* @param id id
* @param name 姓名
* @Date: 2020/2/13 下午12:06
* @Return: int
* @Throws:
*/
int updateName(int id, String name);
}
UserServiceImpl
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luoyu.staticmultipledatasources.entity.User;
import com.luoyu.staticmultipledatasources.mapper.db1.UserMapper;
import com.luoyu.staticmultipledatasources.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
/**
* <p>
* 服務實現(xiàn)類
* </p>
*
* @author jinhaoxun
* @since 2020-02-13
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
@Resource
private UserMapper userMapper;
/**
* @Author: jinhaoxun
* @Description:
* @param id id
* @Date: 2020/2/13 下午12:06
* @Throws:
*/
@Override
public User selectById(Integer id) {
return userMapper.selectById(id);
}
/**
* @Author: jinhaoxun
* @Description:
* @param id id
* @param name 姓名
* @Date: 2020/2/13 下午12:06
* @Return: int
* @Throws:
*/
@Transactional(value = "db1TransactionManger")
@Override
public int updateName(int id, String name) {
int count = userMapper.updateName(id, name);
int i = 1/0;
return count;
}
}
ITaskService
import com.baomidou.mybatisplus.extension.service.IService;
import com.luoyu.staticmultipledatasources.entity.Task;
/**
* <p>
* 服務類
* </p>
*
* @author jinhaoxun
* @since 2020-02-13
*/
public interface ITaskService extends IService<Task> {
/**
* @Author: jinhaoxun
* @Description:
* @param id id
* @Date: 2020/2/13 下午12:06
* @Throws:
*/
Task selectById(Integer id);
/**
* @Author: jinhaoxun
* @Description:
* @param id id
* @param name 姓名
* @Date: 2020/2/13 下午12:06
* @Return: int
* @Throws:
*/
int updateName(int id, String name);
}
TaskServiceImpl
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luoyu.staticmultipledatasources.entity.Task;
import com.luoyu.staticmultipledatasources.mapper.db2.TaskMapper;
import com.luoyu.staticmultipledatasources.service.ITaskService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
/**
* <p>
* 服務實現(xiàn)類
* </p>
*
* @author jinhaoxun
* @since 2020-02-13
*/
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements ITaskService {
@Resource
private TaskMapper taskMapper;
/**
* @Author: jinhaoxun
* @Description:
* @param id id
* @Date: 2020/2/13 下午12:06
* @Throws:
*/
@Override
public Task selectById(Integer id) {
return taskMapper.selectById(id);
}
/**
* @Author: jinhaoxun
* @Description:
* @param id id
* @param name 姓名
* @Date: 2020/2/13 下午12:06
* @Return: int
* @Throws:
*/
@Transactional(value = "db2TransactionManger")
@Override
public int updateName(int id, String name) {
int count = taskMapper.updateName(id, name);
int i = 1/0;
return count;
}
}
第九步坎吻,創(chuàng)建TaskController,UserController宇葱,如下
TaskController
import com.luoyu.staticmultipledatasources.entity.Task;
import com.luoyu.staticmultipledatasources.service.ITaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author jinhaoxun
* @since 2020-02-13
*/
@RestController
public class TaskController {
@Autowired
private ITaskService iTaskService;
/**
* 查詢db2
*/
@GetMapping(value = "/task")
public Task getTaskById(@RequestParam("id") Integer id) {
return iTaskService.selectById(id);
}
/**
* 測試事物
*/
@PutMapping(value = "/task")
public int updateName(@RequestParam("id") Integer id, @RequestParam("name") String name) {
return iTaskService.updateName(id, name);
}
}
UserController
import com.luoyu.staticmultipledatasources.entity.User;
import com.luoyu.staticmultipledatasources.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author jinhaoxun
* @since 2020-02-13
*/
@RestController
public class UserController {
@Autowired
private IUserService iUserService;
/**
* 查詢db1
*/
@GetMapping(value = "/user")
public User getUserById(@RequestParam("id") Integer id) {
return iUserService.selectById(id);
}
/**
* 測試事物
*/
@PutMapping(value = "/user")
public int updateName(@RequestParam("id") Integer id, @RequestParam("name") String name) {
return iUserService.updateName(id, name);
}
}
第十步瘦真,啟動項目,使用postman進行測試黍瞧,如下
測試查db1诸尽,使用GET請求http://localhost:8092/user?id=2
image.png
測試db1事務,修改報錯后再查db1印颤,發(fā)現(xiàn)事務回滾了您机,使用PUT請求http://localhost:8092/user?id=2&name=test999
image.png
測試查db2,使用GET請求http://localhost:8092/task?id=2
image.png
測試db2事務年局,修改報錯后再查db2际看,發(fā)現(xiàn)事務回滾了,使用PUT請求http://localhost:8092/task?id=2&name=test999
image.png