dynamic+sharding-jdbc +springboot 2.4.4配置

在这里插入图片描述

导入依赖

<!-- dynamic-datasource 多数据源 -->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
                <version>3.4.1</version>
            </dependency>
            <!-- shardingsphere -->
            <dependency>
                <groupId>org.apache.shardingsphere</groupId>
                <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
                <version>4.1.1</version>
            </dependency>

配置yml

spring:
  shardingsphere:
    # 展示修改以后的sql语句
    props:
      sql.show: true
    datasource:
      names: ds0
      ds0:
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.zaxxer.hikari.HikariDataSource
        jdbc-url: jdbc:mysql://39.98.91.88:443/test?allowMultiQueries=true
        username: 
        password: 
        #jdbc-url: jdbc:mysql://localhost:3306/dev?serverTimezone=UTC&characterEncoding=UTF-8
        #username: root
        #password: 
    sharding:
      ## 默认数据源
      default-data-source-name: ds0
      tables:
        user_order:
          actual-data-nodes: ds0.user_order_$->{0..5}
          table-strategy:
            inline:
              sharding-column: user_mark
              algorithm-expression: user_order_$->{Math.abs(user_mark.hashCode()) % 6}
        order_detail:
          actual-data-nodes: ds0.order_detail_$->{0..5}
          table-strategy:
            inline:
              sharding-column: order_id
              algorithm-expression: order_detail_$->{Math.abs(order_id.hashCode()) % 6}
          keyGenerator: # 指定表的主键生成策略为SNOWFLAKE
            type: SNOWFLAKE  #主键生成策略为SNOWFLAKE
            column: id  #指定主键
        order_item_info:
          actual-data-nodes: ds0.order_item_info_$->{0..5}
          table-strategy:
            inline:
              sharding-column: order_id
              algorithm-expression: order_item_info_$->{Math.abs(order_id.hashCode()) % 6}
          keyGenerator:
            type: SNOWFLAKE
            column: id
        order_jd_waybill:
          actual-data-nodes: ds0.order_jd_waybill_$->{0..5}
          table-strategy:
            inline:
              sharding-column: id
              algorithm-expression: order_jd_waybill_$->{id % 6}
          keyGenerator: # 指定表的主键生成策略为SNOWFLAKE
            type: SNOWFLAKE  #主键生成策略为SNOWFLAKE
            column: id  #指定主键
        order_third_waybill:
          actual-data-nodes: ds0.order_third_waybill_$->{0..5}
          table-strategy:
            inline:
              sharding-column: id
              algorithm-expression: order_third_waybill_$->{id % 6}
          keyGenerator: # 指定表的主键生成策略为SNOWFLAKE
            type: SNOWFLAKE  #主键生成策略为SNOWFLAKE
            column: id  #指定主键
      # 设置绑定表,左边的为主表,右边的为子表,可以配置多个,用集合的方式
      binding-tables:
        - order_detail,order_item_info

  # 动态数据源配置
  datasource:
    dynamic:
      datasource:
        master:
          driver-class-name: com.mysql.cj.jdbc.Driver
          type: com.zaxxer.hikari.HikariDataSource
          url: jdbc:mysql://39.98.91.88:443/test?allowMultiQueries=true
          username: 
          password: 
          #url: jdbc:mysql://localhost:3306/dev?serverTimezone=UTC&characterEncoding=UTF-8
          #username: root
          #password: 
      # 指定默认数据源名称
      primary: master

config配置文件

import cn.nascent.jdm.common.constant.common.DataSouceConstant;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.provider.AbstractDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源配置
 * 使用dynamic-datasource与shardingshpere-jdbc结合,需要分片的表单独交给shardingsphere处理,
 * 再经由dynamic-datasource管理,弥补shardingsphere在sql上的不支持项(union等)
 *
 * @author 
 * @since
 */
@Configuration
@AutoConfigureBefore({DynamicDataSourceAutoConfiguration.class, SpringBootConfiguration.class})
public class MyDataSourceConfiguration {

    @Resource
    private DynamicDataSourceProperties properties;

    /**
     * 未使用分片, 脱敏的名称(默认): shardingDataSource
     * 使用了主从: masterSlaveDataSource
     * 根据自己场景修改注入
     */
    @Resource(name = "shardingDataSource")
    @Lazy
    DataSource shardingDataSource;

    @Bean
    public DynamicDataSourceProvider dynamicDataSourceProvider() {
        return new AbstractDataSourceProvider() {
            @Override
            public Map<String, DataSource> loadDataSources() {
                Map<String, DataSource> dataSourceMap = new HashMap<>(16);
                // 将sharding的数据源交给dynamic管理,数据源名字自定义
                dataSourceMap.put(DataSouceConstant.SHARDING_SPHERE, shardingDataSource);
                //打开下面的代码可以把 shardingJdbc 内部管理的子数据源也同时添加到动态数据源里 (根据自己需要选择开启)
                // dataSourceMap.putAll(((ShardingSphereDataSource) shardingDataSource).getDataSourceMap());
                return dataSourceMap;
            }
        };
    }

    /**
     * 将动态数据源设置为首选的
     * 当spring存在多个数据源时, 自动注入的是首选的对象
     * 设置为主要的数据源之后,就可以支持shardingjdbc原生的配置方式了
     * 3.4.0版本及以上使用以下方式注入,老版本请阅读文档  进阶-手动注入多数据源
     */
    @Primary
    @Bean
    public DataSource dataSource() {
        DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
        dataSource.setPrimary(properties.getPrimary());
        dataSource.setStrict(properties.getStrict());
        dataSource.setStrategy(properties.getStrategy());
        dataSource.setP6spy(properties.getP6spy());
        dataSource.setSeata(properties.getSeata());
        return dataSource;
    }
}

调用数据源

  1. 使用@DS注解切换数据源,@DS可以作用在接口实现类上,也可以作用在方法上,作用在mapper等无效,注意如果B方法被A方法调用,且A开启了事务,则B方法想切换数据源一定要添加新事务@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class),如果B开启新事务,B会被A事务覆盖,导致B无法切换数据源,参考文章:点我跳转到新文章,正确使用如下:
  2. @DS(value = DataSouceConstant.SHARDING_SPHERE) 注解的值填Config配置中数据源的值,这个值是自己自定义的【dataSourceMap.put(DataSouceConstant.SHARDING_SPHERE, shardingDataSource)】。
    A方法:
@Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean orderSyncJob(String masterId) {
    // 更新数据
        orderDetailService.saveOrUpdateOrderDetailList(popOrderDetailDTOList);
    }

B方法

	@Override
    @DS(value = DataSouceConstant.SHARDING_SPHERE)
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public boolean saveOrUpdateOrderDetailList(List<PopOrderDetailDTO> popOrderDetailDTOList) {
        if (CollectionUtil.isNotEmpty(popOrderDetailDTOList)) {
            this.getBaseMapper().insertOrUpdateBatchOrder(BeanConversionUtils.beanListConversion(popOrderDetailDTOList, OrderDetailDO.class));
        }
        return true;
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是 Spring Boot 集成 Sharding-JDBC + Mybatis-Plus 实现分库分表的实战代码: 1. 添加依赖 在 `pom.xml` 文件中添加以下依赖: ```xml <dependencies> <!-- Sharding-JDBC --> <dependency> <groupId>io.shardingsphere</groupId> <artifactId>sharding-jdbc-core</artifactId> <version>4.1.1</version> </dependency> <!-- Mybatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3</version> </dependency> <!-- MySQL 驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.24</version> </dependency> </dependencies> ``` 2. 配置数据源 在 `application.yml` 文件中配置数据源: ```yaml spring: datasource: # 主库 master: url: jdbc:mysql://localhost:3306/db_master?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver # 从库 slave: url: jdbc:mysql://localhost:3306/db_slave?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver ``` 3. 配置 Sharding-JDBC 在 `application.yml` 文件中配置 Sharding-JDBC: ```yaml spring: shardingsphere: datasource: names: master, slave # 数据源名称 master: type: com.zaxxer.hikari.HikariDataSource slave: type: com.zaxxer.hikari.HikariDataSource config: sharding: tables: user: actualDataNodes: master.user_$->{0..1} # 分表规则,user_0 和 user_1 表 tableStrategy: inline: shardingColumn: id algorithmExpression: user_$->{id % 2} # 分表规则,根据 id 取模 databaseStrategy: inline: shardingColumn: id algorithmExpression: master # 分库规则,根据 id 取模 bindingTables: - user # 绑定表,即需要进行分库分表的表 ``` 4. 配置 Mybatis-Plus 在 `application.yml` 文件中配置 Mybatis-Plus: ```yaml mybatis-plus: configuration: map-underscore-to-camel-case: true # 下划线转驼峰 ``` 5. 编写实体类 创建 `User` 实体类,用于映射数据库中的 `user` 表: ```java @Data public class User { private Long id; private String name; private Integer age; } ``` 6. 编写 Mapper 接口 创建 `UserMapper` 接口,用于定义操作 `user` 表的方法: ```java @Mapper public interface UserMapper extends BaseMapper<User> { } ``` 7. 编写 Service 类 创建 `UserService` 类,用于调用 `UserMapper` 接口中的方法: ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User getById(Long id) { return userMapper.selectById(id); } public boolean save(User user) { return userMapper.insert(user) > 0; } public boolean updateById(User user) { return userMapper.updateById(user) > 0; } public boolean removeById(Long id) { return userMapper.deleteById(id) > 0; } } ``` 8. 测试 在 `UserController` 类中进行测试: ```java @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/user") public User getUser(Long id) { return userService.getById(id); } @PostMapping("/user") public boolean addUser(@RequestBody User user) { return userService.save(user); } @PutMapping("/user") public boolean updateUser(@RequestBody User user) { return userService.updateById(user); } @DeleteMapping("/user") public boolean removeUser(Long id) { return userService.removeById(id); } } ``` 启动应用程序,访问 `http://localhost:8080/user?id=1` 可以得到 `id` 为 1 的用户信息。访问 `http://localhost:8080/user` 并传入用户信息,可以添加用户。访问 `http://localhost:8080/user` 并传入更新后的用户信息,可以更新用户信息。访问 `http://localhost:8080/user?id=1` 并使用 DELETE 方法,可以删除用户。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值