springboot集成shardingSphere

springboot集成shardingSphere,demo地址:https://github.com/MeihaoLife/demo-dubbo

1、引入shardingSphere的sharding-jdbc的相关依赖,此处直接引入starter

        <!-- shardingSphere 依赖 -->
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
            <version>4.1.1</version>
        </dependency>

        <!-- mybatis plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>

        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

2、配置sharding-jdbc的分库分表配置

server:
  port: 9081
spring:
  main:
    allow-bean-definition-overriding: true
  shardingsphere: # shardingsphere 分库分表 读写分离配置
    datasource: # 数据源配置
      names: m-db1,m-db2,m-db3,s-db1,s-db2,s-db3
      m-db1:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf-8&&serverTimezone=GMT%2B8
        username: root
        password: 123456
      m-db2:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://localhost:3306/db2?characterEncoding=utf-8&&serverTimezone=GMT%2B8
        username: root
        password: 123456
      m-db3:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://localhost:3306/db3?characterEncoding=utf-8&&serverTimezone=GMT%2B8
        username: root
        password: 123456
      s-db1:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://localhost:3307/db1?characterEncoding=utf-8&&serverTimezone=GMT%2B8
        username: root
        password: 123456
      s-db2:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://localhost:3307/db2?characterEncoding=utf-8&&serverTimezone=GMT%2B8
        username: root
        password: 123456
      s-db3:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://localhost:3307/db3?characterEncoding=utf-8&&serverTimezone=GMT%2B8
        username: root
        password: 123456

    sharding:
      default-database-strategy: # 分库
        inline:
          sharding-column: user_id # 分库字段
          algorithm-expression: m-db$->{user_id%3+1} # 分库规则
      tables: # 分表
        t_user_operate_log:
          actual-data-nodes: m-db$->{1..3}.t_user_operate_log_$->{0..1}
          table-strategy:
            inline:
              sharding-column: user_id # 分表字段
              algorithm-expression: t_user_operate_log_$->{user_id%2} # 分表规则
      master-slave-rules: #主从配置,读写分离配置,读走从库(从库可以配置多个),写主库
        m-db1:
          master-data-source-name: m-db1
          slave-data-source-names: s-db1
        m-db2:
          master-data-source-name: m-db2
          slave-data-source-names: s-db2
        m-db3:
          master-data-source-name: m-db3
          slave-data-source-names: s-db3
    props: # 打印sql
      sql:
        show: true

mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true # 下划线转驼峰

3、数据库操作代码

@Data
@Builder
@SuppressWarnings("serial")
public class UserOperateLogDTO implements Serializable {

    private Long userId;

    private Date operateTime;

    private String operateDesc;

    private Byte operateResult;

}
@Data
@Accessors(chain = true)
@TableName("t_user_operate_log")
public class UserOperateLogModel extends Model<UserOperateLogModel> {

    private Long id;

    private Long userId;

    private Date operateTime;

    private String operateDesc;

    private Byte operateResult;

    private String handlerClass;

    private String handlerMethod;

}
/**
 * @ClassName: UserOperateLogService
 * @Description: TODO
 * @Author: zhānghào
 * @Date: 2021/1/13 5:36 下午
 * @Version: v1.0
 **/
public interface UserOperateLogService {

    boolean save(UserOperateLogDTO entity);

    List<UserOperateLogDTO> getList(UserOperateLogDTO userOperateLogModel);
}
@Service
public class UserOperateLogServiceImpl extends ServiceImpl<UserOperateLogMapper, UserOperateLogModel> implements UserOperateLogService {

    // 数据写入主库,分库分表
    @Override
    public boolean save(UserOperateLogDTO userOperateLogDTO) {
        UserOperateLogModel model = new UserOperateLogModel();
        BeanUtils.copyProperties(userOperateLogDTO, model);
        return super.save(model);
    }

    // 数据读取从库,分库分表
    @Override
    public List<UserOperateLogDTO> getList(UserOperateLogDTO userOperateLogDTO) {

        UserOperateLogModel userOperateLogModel = new UserOperateLogModel();
        BeanUtils.copyProperties(userOperateLogDTO, userOperateLogModel);
        if (userOperateLogModel.getUserId() == null) {
            return Collections.emptyList();
        }
        QueryWrapper<UserOperateLogModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userOperateLogModel.getUserId());
        List<UserOperateLogModel> userOperateLogModels = this.baseMapper.selectList(queryWrapper);
        if (userOperateLogModels.size() == 0) {
            return Collections.emptyList();
        }
        List<UserOperateLogDTO> returnList = new ArrayList<>(userOperateLogModels.size());
        userOperateLogModels.forEach(model -> returnList.add(UserOperateLogDTO.builder()
                .userId(model.getUserId())
                .operateTime(model.getOperateTime())
                .operateDesc(model.getOperateDesc())
                .operateResult(model.getOperateResult()).build()));

        return returnList;
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot集成ShardingSphere的步骤如下: 1. 添加ShardingSphere依赖 在pom.xml文件中添加ShardingSphere的依赖: ``` <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-jdbc-spring-boot-starter</artifactId> <version>${shardingsphere.version}</version> </dependency> ``` 2. 配置ShardingSphere 在application.yml文件中配置ShardingSphere的数据源和分片规则: ``` spring: shardingsphere: datasource: names: ds, ds1 ds: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.jdbc.Driver jdbc-url: jdbc:mysql://localhost:3306/db username: root password: root ds1: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.jdbc.Driver jdbc-url: jdbc:mysql://localhost:3306/db1 username: root password: root sharding: tables: user: actual-data-nodes: ds$->{..1}.user_$->{..1} table-strategy: inline: sharding-column: id algorithm-expression: user_$->{id % 2} ``` 3. 编写代码 在代码中使用ShardingSphere的数据源进行数据库操作: ``` @Autowired private DataSource dataSource; public void addUser(User user) { String sql = "insert into user (id, name, age) values (?, ?, ?)"; try (Connection conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) { ps.setLong(1, user.getId()); ps.setString(2, user.getName()); ps.setInt(3, user.getAge()); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } ``` 以上就是Spring Boot集成ShardingSphere的基本步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值