欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

MyBatis-Flex+ShardingSphere-JDBC多數(shù)據(jù)源分庫(kù)分表實(shí)現(xiàn)

 更新時(shí)間:2024年10月14日 11:22:53   作者:墨辰李  
本文介紹了使用MyBatis-Flex和ShardingSphere-JDBC實(shí)現(xiàn)多數(shù)據(jù)源分庫(kù)分表的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

1、目的

用于動(dòng)態(tài)配置ShardingSphere-JDBC實(shí)現(xiàn)配置化分庫(kù)分表

2、實(shí)現(xiàn)

2-1、導(dǎo)入MyBatis-Flex和ShardingSphere-JDBC的相關(guān)依賴

        <dependency>
            <groupId>com.mybatis-flex</groupId>
            <artifactId>mybatis-flex-spring-boot-starter</artifactId>
            <version>1.9.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
            <version>5.1.1</version>
        </dependency>

2-2、配置初始化的數(shù)據(jù)庫(kù)連接用來(lái)加載配置,當(dāng)然用配置中心來(lái)保存初始化數(shù)據(jù)的配置

spring.datasource.ds1.jdbc-url=jdbc:mysql://localhost/test?allowPublicKeyRetrieval=true
spring.datasource.ds1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.ds1.username=root
spring.datasource.ds1.password=123456
spring.datasource.ds1.type=com.zaxxer.hikari.HikariDataSource

2-3、初始化數(shù)據(jù)源進(jìn)行配置查詢

初始化數(shù)據(jù)源配置類:

package com.mochenli.shardingshere.config;
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 javax.sql.DataSource;

/**
 * @author: MoChenLi
 * @description:
 * @createTime: 2024-06-27 21:23
 */
@Configuration
public class DataSourceConfig {
    /**
     * 根據(jù)配置文件構(gòu)建數(shù)據(jù)源
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.ds1")
    public DataSource dataSourceOne(){
      return DataSourceBuilder.create().build();
    }

}

數(shù)據(jù)配置表以及數(shù)據(jù)

/*
 Navicat Premium Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 80034 (8.0.34)
 Source Host           : localhost:3306
 Source Schema         : test

 Target Server Type    : MySQL
 Target Server Version : 80034 (8.0.34)
 File Encoding         : 65001

 Date: 29/06/2024 17:52:36
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for databaseconfig
-- ----------------------------
DROP TABLE IF EXISTS `databaseconfig`;
CREATE TABLE `databaseconfig`  (
  `id` int NOT NULL AUTO_INCREMENT COMMENT '主鍵唯一標(biāo)識(shí)',
  `jdbc_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '數(shù)據(jù)庫(kù)連接',
  `driver_class_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '數(shù)據(jù)庫(kù)連接驅(qū)動(dòng)',
  `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '數(shù)據(jù)庫(kù)連接用戶名',
  `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '數(shù)據(jù)庫(kù)連接密碼',
  `Connection_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '數(shù)據(jù)庫(kù)連接名稱',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of databaseconfig
-- ----------------------------
INSERT INTO `databaseconfig` VALUES (1, 'jdbc:mysql://192.168.157.129:3310/db_order?allowPublicKeyRetrieval=true', 'com.mysql.cj.jdbc.Driver', 'root', '123456', 'server-order0');
INSERT INTO `databaseconfig` VALUES (2, 'jdbc:mysql://192.168.157.129:3311/db_order?allowPublicKeyRetrieval=true', 'com.mysql.cj.jdbc.Driver', 'root', '123456', 'server-order1');

SET FOREIGN_KEY_CHECKS = 1;

數(shù)據(jù)庫(kù)配置對(duì)象類

package com.mochenli.shardingshere.entity;
import com.mybatisflex.annotation.Id;
import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.annotation.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
 * @author: MoChenLi
 * @description:
 * @createTime: 2024-06-29 17:28
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table("DataBaseConfig")
public class DataBaseConfig {

    @Id(keyType = KeyType.Auto)
    private Integer id;

    private String jdbcUrl;

    private String username;

    private String password;

    private String driverClassName;

    private String connectionName;
}

mapper類

package com.mochenli.shardingshere.mapper;
import com.mochenli.shardingshere.entity.DataBaseConfig;
import com.mybatisflex.core.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
 * @author: MoChenLi
 * @description:
 * @createTime: 2024-06-29 17:31
 */
@Mapper
public interface DataBaseConfigMapper extends BaseMapper<DataBaseConfig> {
}

2-4、初始化ShardingDataSource數(shù)據(jù)源實(shí)現(xiàn)分庫(kù)分表

分片算法可查看鏈接

package com.mochenli.shardingshere.config;
import com.mochenli.shardingshere.entity.DataBaseConfig;
import com.mochenli.shardingshere.mapper.DataBaseConfigMapper;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.datasource.FlexDataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.shardingsphere.driver.api.ShardingSphereDataSourceFactory;
import org.apache.shardingsphere.infra.config.algorithm.ShardingSphereAlgorithmConfiguration;
import org.apache.shardingsphere.infra.config.mode.ModeConfiguration;
import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;
import org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration;
import org.apache.shardingsphere.sharding.api.config.strategy.keygen.KeyGenerateStrategyConfiguration;
import org.apache.shardingsphere.sharding.api.config.strategy.sharding.ShardingStrategyConfiguration;
import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.*;
/**
 * @author: MoChenLi
 * @description:
 * @createTime: 2024-06-19 13:53
 */
@Configuration
public class ShardingConfig {

     private DataBaseConfigMapper dataBaseConfigMapper;

    public ShardingConfig(DataBaseConfigMapper dataBaseConfigMapper) throws SQLException {
        this.dataBaseConfigMapper = dataBaseConfigMapper;
        FlexDataSource flexDataSource = FlexGlobalConfig.getDefaultConfig()
                .getDataSource();
        flexDataSource.addDataSource("getShardingDataSource",getShardingDataSource());
    }
    /**
     * 配置shardingsphere的內(nèi)存模式
     * @return
     */
    @Bean
    public ModeConfiguration getModeConfiguration() {
        ModeConfiguration modeConfiguration = new ModeConfiguration("Memory", null, false);
        return modeConfiguration;
    }
    /**
     * 構(gòu)建ShardingDataSource數(shù)據(jù)源
     * @return
     * @throws SQLException
     */
    public DataSource getShardingDataSource() throws SQLException {
        //查詢數(shù)據(jù)庫(kù)的數(shù)據(jù)連接配置設(shè)置到dataSourceMap當(dāng)中
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        List<DataBaseConfig> dataBaseConfigs = dataBaseConfigMapper.selectAll();
        for (DataBaseConfig dataBaseConfig : dataBaseConfigs) {
            DataSource dataSource = createDataSource(dataBaseConfig);
            dataSourceMap.put(dataBaseConfig.getConnectionName(), dataSource);
        }
        //以下分片配置的規(guī)則也可持久化從數(shù)據(jù)庫(kù)查詢出來(lái)進(jìn)行配置 此處用于演示所需即靜態(tài)配置
        // 配置分片規(guī)則
        ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
        //算法相關(guān)配置
        Map<String, ShardingSphereAlgorithmConfiguration> shardingSphereAlgorithmConfigurations = new HashMap<>();
        Properties properties = new Properties();
        properties.put("algorithm-expression","server-order$->{user_id % 2}");
        ShardingSphereAlgorithmConfiguration shardingSphereAlgorithmConfiguration =  new ShardingSphereAlgorithmConfiguration("INLINE",properties);
        Properties properties1 = new Properties();
        properties1.put("sharding-count","2");
        ShardingSphereAlgorithmConfiguration shardingSphereAlgorithmConfiguration1 =  new ShardingSphereAlgorithmConfiguration("MOD",properties1);
        Properties properties2 = new Properties();
        properties2.put("sharding-count","2");
        ShardingSphereAlgorithmConfiguration shardingSphereAlgorithmConfiguration2 =  new ShardingSphereAlgorithmConfiguration("HASH_MOD",properties2);
        shardingSphereAlgorithmConfigurations.put("alg_inline_userid",shardingSphereAlgorithmConfiguration);
        shardingSphereAlgorithmConfigurations.put("alg_mod",shardingSphereAlgorithmConfiguration1);
        shardingSphereAlgorithmConfigurations.put("alg_hash_mod",shardingSphereAlgorithmConfiguration2);
        shardingRuleConfig.setShardingAlgorithms(shardingSphereAlgorithmConfigurations);
        //分庫(kù)分表策略配置
        Collection<ShardingTableRuleConfiguration> shardingTableRuleConfigurations = new ArrayList<>();
        //分庫(kù)策略
        ShardingTableRuleConfiguration shardingTableRuleConfiguration = new ShardingTableRuleConfiguration("t_order","server-order$->{0..1}.t_order$->{0..1}");
        ShardingStrategyConfiguration shardingStrategyConfiguration = new StandardShardingStrategyConfiguration("user_id","alg_mod");
        shardingTableRuleConfiguration.setDatabaseShardingStrategy(shardingStrategyConfiguration);
        //分表策略
        ShardingStrategyConfiguration shardingStrategyConfigurationtable = new StandardShardingStrategyConfiguration("order_no","alg_hash_mod");
        shardingTableRuleConfiguration.setTableShardingStrategy(shardingStrategyConfigurationtable);
        shardingTableRuleConfigurations.add(shardingTableRuleConfiguration);
        shardingRuleConfig.setTables(shardingTableRuleConfigurations);
        //配置主鍵算法生成策略
        Map<String, ShardingSphereAlgorithmConfiguration> keyGenerators = new HashMap<>();
        ShardingSphereAlgorithmConfiguration shardingSphereAlgorithmConfigurationsk =  new ShardingSphereAlgorithmConfiguration("SNOWFLAKE",null);
        keyGenerators.put("alg_snowflake",shardingSphereAlgorithmConfigurationsk);
        shardingRuleConfig.setKeyGenerators(keyGenerators);
        //分布式id
        KeyGenerateStrategyConfiguration keyGenerateStrategyConfiguration =new KeyGenerateStrategyConfiguration("id","alg_snowflake");
        shardingTableRuleConfiguration.setKeyGenerateStrategy(keyGenerateStrategyConfiguration);
        //屬性設(shè)置運(yùn)行sql打印顯示
        Properties properties3 = new Properties();
        properties3.put("sql-show",true);
        // 創(chuàng)建ShardingDataSource
        DataSource dataSources = ShardingSphereDataSourceFactory.createDataSource(dataSourceMap, Collections.singleton(shardingRuleConfig),properties3 );
        return dataSources;
    }
    /**
     * 創(chuàng)建數(shù)據(jù)源連接
     * @param dataBaseConfig
     * @return
     */
    public static DataSource createDataSource(DataBaseConfig dataBaseConfig)  {
        // 創(chuàng)建數(shù)據(jù)源,這里需要根據(jù)實(shí)際情況創(chuàng)建,例如使用HikariCP、Druid等連接池
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(dataBaseConfig.getDriverClassName());
        dataSource.setJdbcUrl(dataBaseConfig.getJdbcUrl());
        dataSource.setUsername(dataBaseConfig.getUsername());
        dataSource.setPassword(dataBaseConfig.getPassword());
        //不使用連接池
        //DriverManagerDataSource dataSource1 = new DriverManagerDataSource();
        //dataSource1.setDriverClassName(dataBaseConfig.getDriverClassName());
        //dataSource1.setUrl(dataBaseConfig.getJdbcUrl());
        //dataSource1.setUsername(dataBaseConfig.getUsername());
        //dataSource1.setPassword(dataBaseConfig.getPassword());
        return dataSource;
    }
}

2-5、兩個(gè)數(shù)據(jù)庫(kù)連接server-order0和server-order1的表結(jié)構(gòu)如下:分別在兩個(gè)庫(kù)當(dāng)中運(yùn)行

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for t_order0
-- ----------------------------
DROP TABLE IF EXISTS `t_order0`;
CREATE TABLE `t_order0`  (
  `id` bigint NOT NULL,
  `order_no` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `user_id` bigint NULL DEFAULT NULL,
  `amount` decimal(10, 2) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;


-- ----------------------------
-- Table structure for t_order1
-- ----------------------------
DROP TABLE IF EXISTS `t_order1`;
CREATE TABLE `t_order1`  (
  `id` bigint NOT NULL,
  `order_no` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `user_id` bigint NULL DEFAULT NULL,
  `amount` decimal(10, 2) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

2-6、實(shí)體這個(gè)@Table(“t_order”)是邏輯表名ShardingConfig分庫(kù)策略時(shí)設(shè)置的

package com.mochenli.shardingshere.entity;
import com.mybatisflex.annotation.Id;
import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.annotation.Table;
import lombok.Data;
import java.math.BigDecimal;
/**
 * @author: MoChenLi
 * @description:
 * @createTime: 2024-06-18 17:15
 */
@Table("t_order")
@Data
public class Order {
    @Id(keyType = KeyType.Auto)
    private Long id;
    private String orderNo;
    private Long userId;
    private BigDecimal amount;
}

2-7、mapper

package com.mochenli.shardingshere.mapper;
import com.mochenli.shardingshere.entity.Order;
import com.mybatisflex.core.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
 * @author: MoChenLi
 * @description:
 * @createTime: 2024-06-18 17:18
 */
@Mapper
public interface OrderMapper extends BaseMapper<Order> {
}

3、測(cè)試

3-1、測(cè)試分庫(kù)分表的新增

package com.mochenli.shardingshere.controller;

import com.mochenli.shardingshere.entity.Order;
import com.mochenli.shardingshere.mapper.OrderMapper;
import com.mybatisflex.core.datasource.DataSourceKey;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: MoChenLi
 * @description:
 * @createTime: 2024-06-29 18:11
 */
@RestController
@AllArgsConstructor
public class TestController {
   private final   OrderMapper orderMapper;
    /**
     * id是用分布式id雪花算法 所以不填
     * 測(cè)試新增   因?yàn)榍懊媾渲檬歉鶕?jù)user_id進(jìn)行分庫(kù) 分庫(kù)算法是:取模分片,算法類型:MOD  分片數(shù)量是 2
     * 分表算法是根據(jù) order_no 進(jìn)行分表  分表算法是 哈希取模分片算法,類型:HASH_MOD  分片數(shù)量是 2
     */
    @GetMapping("/testAddOrder")
    public String addTOrder(){
        //切換數(shù)據(jù)源 使用ShardingDataSource數(shù)據(jù)源
        DataSourceKey.use("getShardingDataSource");
        //進(jìn)行分庫(kù)分表插入
        for (int i = 1; i <=60; i++) {
            Order order = new Order();
            order.setUserId(Long.valueOf(i));
            order.setOrderNo("分表算法"+i);
            orderMapper.insert(order);
        }
        return "success";
    }
}

結(jié)果如下所示:

image.png

server_order0.t_order0

image.png

server_order0.t_order1

image.png

server_order1.t_order0

image.png

server_order1.t_order1

image.png

3-2、測(cè)試分頁(yè)查詢:

package com.mochenli.shardingshere.controller;

import com.mochenli.shardingshere.entity.Order;
import com.mochenli.shardingshere.mapper.OrderMapper;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: MoChenLi
 * @description:
 * @createTime: 2024-06-29 18:11
 */
@RestController
@AllArgsConstructor
public class TestController {
   private final   OrderMapper orderMapper;
    
      /**
     * 測(cè)試分頁(yè)查詢
     * @return
     */
    @GetMapping("/testPageOrder")
    public Page<Order> getPage(){
        //切換數(shù)據(jù)源 使用ShardingDataSource數(shù)據(jù)源
        DataSourceKey.use("getShardingDataSource");
        //進(jìn)行分頁(yè)查詢
        Page<Order> page = new Page<>();
        page.setPageNumber(1);
        page.setPageSize(27);
        Page<Order> paginate = orderMapper.paginate(page, new QueryWrapper());
        return paginate;
    

}

結(jié)果如下:

image.png

3-3、測(cè)試事務(wù)問(wèn)題

1、正常情況

package com.mochenli.shardingshere.controller;

import com.mochenli.shardingshere.entity.DataBaseConfig;
import com.mochenli.shardingshere.entity.Order;
import com.mochenli.shardingshere.mapper.DataBaseConfigMapper;
import com.mochenli.shardingshere.mapper.OrderMapper;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: MoChenLi
 * @description:
 * @createTime: 2024-06-29 18:11
 */
@RestController
@AllArgsConstructor
public class TestController {
   private final   OrderMapper orderMapper;
   private  final DataBaseConfigMapper dataBaseConfigMapper;
  
    /**
     * 測(cè)試事務(wù)問(wèn)題
     * 正常情況
     */
    @GetMapping("/testTransaction")
    public Map<String,Object> testTransaction(){
        Map<String,Object> map = new HashMap<>();
        List<DataBaseConfig> dataBaseConfigs = dataBaseConfigMapper.selectAll();
        map.put("dataBaseConfigs",dataBaseConfigs);
        DataSourceKey.clear();//清除數(shù)據(jù)源
        //切換數(shù)據(jù)源 使用ShardingDataSource數(shù)據(jù)源
        DataSourceKey.use("getShardingDataSource");
        List<Order> orders = orderMapper.selectAll();
        map.put("orders",orders);
        return map;
    }

}

結(jié)果:

image.png

2、出錯(cuò)進(jìn)行事務(wù)回滾情況一

package com.mochenli.shardingshere.controller;

import com.mochenli.shardingshere.entity.DataBaseConfig;
import com.mochenli.shardingshere.entity.Order;
import com.mochenli.shardingshere.mapper.DataBaseConfigMapper;
import com.mochenli.shardingshere.mapper.OrderMapper;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: MoChenLi
 * @description:
 * @createTime: 2024-06-29 18:11
 */
@RestController
@AllArgsConstructor
public class TestController {
    private final OrderMapper orderMapper;
    private final DataBaseConfigMapper dataBaseConfigMapper;
    /**
     * 測(cè)試事務(wù)問(wèn)題
     * 報(bào)錯(cuò)情況一  不分庫(kù)的數(shù)據(jù)源報(bào)錯(cuò)  回滾
     */
    @GetMapping("/testTransactionError")
    @Transactional
    public void testTransactionError() {
        DataBaseConfig dataBaseConfig = new DataBaseConfig();
        dataBaseConfig.setConnectionName("連接名稱");
        dataBaseConfig.setJdbcUrl("連接字符串");
        dataBaseConfig.setUsername("用戶名");
        dataBaseConfig.setPassword("密碼");
        dataBaseConfig.setDriverClassName("驅(qū)動(dòng)");
        //進(jìn)行新增
        dataBaseConfigMapper.insert(dataBaseConfig);
        //模擬報(bào)錯(cuò)
        int i = 10 / 0;
        DataSourceKey.clear();//清除數(shù)據(jù)源
        //切換數(shù)據(jù)源 使用ShardingDataSource數(shù)據(jù)源
        DataSourceKey.use("getShardingDataSource");
        List<Order> orders = orderMapper.selectAll();
    }

}

image.png

image.png

3、出錯(cuò)進(jìn)行事務(wù)回滾情況二

package com.mochenli.shardingshere.controller;

import com.mochenli.shardingshere.entity.DataBaseConfig;
import com.mochenli.shardingshere.entity.Order;
import com.mochenli.shardingshere.mapper.DataBaseConfigMapper;
import com.mochenli.shardingshere.mapper.OrderMapper;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: MoChenLi
 * @description:
 * @createTime: 2024-06-29 18:11
 */
@RestController
@AllArgsConstructor
public class TestController {
    private final OrderMapper orderMapper;
    private final DataBaseConfigMapper dataBaseConfigMapper;

    /**
     * 測(cè)試事務(wù)問(wèn)題
     * 報(bào)錯(cuò)情況二  分庫(kù)分表的數(shù)據(jù)源報(bào)錯(cuò)  回滾
     */
    @GetMapping("/testTransactionError1")
    @Transactional
    public void testTransactionError1() {
        //切換數(shù)據(jù)源 使用ShardingDataSource數(shù)據(jù)源
        DataSourceKey.use("getShardingDataSource");
        for (int i = 1; i <= 5; i++) {
            Order order = new Order();
            //不出錯(cuò) 1%2=1應(yīng)該在server_order1庫(kù)當(dāng)中
            order.setUserId(1L);
           //不出錯(cuò)  "事務(wù)回滾測(cè)試".hashCode() % 2 = 0 應(yīng)該在 t_order0表當(dāng)中;
            order.setOrderNo("事務(wù)回滾測(cè)試");
            orderMapper.insert(order);
        }
        //模擬報(bào)錯(cuò)
        int k = 10 / 0;
        DataSourceKey.clear();//清除數(shù)據(jù)源
        List<DataBaseConfig> dataBaseConfigs = dataBaseConfigMapper.selectAll();
    }

}

結(jié)果回滾了

image.png

補(bǔ)充:mybatis-plus不支持多數(shù)據(jù)源切換,得自己實(shí)現(xiàn),且還得自己進(jìn)行自定義事務(wù)增強(qiáng)

到此這篇關(guān)于MyBatis-Flex+ShardingSphere-JDBC多數(shù)據(jù)源分庫(kù)分表實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)MyBatis-Flex+ShardingSphere-JDBC 分庫(kù)分表內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 深入理解java代碼實(shí)現(xiàn)分治算法

    深入理解java代碼實(shí)現(xiàn)分治算法

    分治算法是一種遞歸算法,它將問(wèn)題劃分為幾個(gè)獨(dú)立的子問(wèn)題,然后遞歸地解決這些子問(wèn)題,最后將子問(wèn)題的解合并起來(lái)得到原問(wèn)題的解,本文詳細(xì)的介紹java分治算法,感興趣的可以了解一下
    2023-09-09
  • Java實(shí)現(xiàn)發(fā)紅包功能

    Java實(shí)現(xiàn)發(fā)紅包功能

    這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)發(fā)紅包功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-11-11
  • mybatis-plus之如何根據(jù)數(shù)據(jù)庫(kù)主鍵定義字段類型

    mybatis-plus之如何根據(jù)數(shù)據(jù)庫(kù)主鍵定義字段類型

    這篇文章主要介紹了mybatis-plus之如何根據(jù)數(shù)據(jù)庫(kù)主鍵定義字段類型問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • 詳解Mybatis中萬(wàn)能的Map和模糊查詢寫法

    詳解Mybatis中萬(wàn)能的Map和模糊查詢寫法

    這篇文章主要介紹了Mybatis中萬(wàn)能的Map和模糊查詢寫法的相關(guān)資料,幫助大家更好的理解和使用Mybatis,感興趣的朋友可以了解下
    2021-03-03
  • springboot自動(dòng)重連Redis的實(shí)現(xiàn)方法

    springboot自動(dòng)重連Redis的實(shí)現(xiàn)方法

    由于網(wǎng)絡(luò)或服務(wù)器問(wèn)題,Redis連接可能會(huì)斷開,導(dǎo)致應(yīng)用程序無(wú)法繼續(xù)正常工作,本文主要介紹了springboot自動(dòng)重連Redis的實(shí)現(xiàn)方法,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-02-02
  • 深入理解java內(nèi)置鎖(synchronized)和顯式鎖(ReentrantLock)

    深入理解java內(nèi)置鎖(synchronized)和顯式鎖(ReentrantLock)

    這篇文章主要介紹了Java多線程之內(nèi)置鎖(synchronized)和顯式鎖(ReentrantLock)的深入理解新的和用法,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-11-11
  • Java  mysql數(shù)據(jù)庫(kù)并進(jìn)行內(nèi)容查詢實(shí)例代碼

    Java mysql數(shù)據(jù)庫(kù)并進(jìn)行內(nèi)容查詢實(shí)例代碼

    這篇文章主要介紹了Java mysql數(shù)據(jù)庫(kù)并進(jìn)行內(nèi)容查詢實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下
    2016-11-11
  • Java中eq、ne、ge、gt、le、lt的含義詳細(xì)解釋

    Java中eq、ne、ge、gt、le、lt的含義詳細(xì)解釋

    Java中的比較運(yùn)算符包括eq(等于)、ne(不等于)、ge(大于或等于)、gt(大于)、le(小于或等于)和lt(小于),這些運(yùn)算符在控制流語(yǔ)句和條件語(yǔ)句中用于判斷條件是否滿足,從而決定程序的執(zhí)行路徑,需要的朋友可以參考下
    2024-11-11
  • SpringBoot單元測(cè)試使用@Test沒(méi)有run方法的解決方案

    SpringBoot單元測(cè)試使用@Test沒(méi)有run方法的解決方案

    這篇文章主要介紹了SpringBoot單元測(cè)試使用@Test沒(méi)有run方法的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • Java9中新增的Collector收集器

    Java9中新增的Collector收集器

    這篇文章主要介紹了Java9中新增的Collector收集器,Collector作為收集器,簡(jiǎn)單來(lái)說(shuō)就是將數(shù)據(jù)或元素收集到一起,并且flatMapping與收集器結(jié)合使用,通過(guò)提供智能元素集合進(jìn)行分組。下文相關(guān)介紹需要的小伙伴可以參考一下
    2022-06-06

最新評(píng)論