第二篇:深入了解认识 ShardingSphere 核心功能

一、深入 ShardingSphere 核心功能

1. 读写分离

  • 目标:配置主从库,实现读请求从从库读取,写请求写入主库。
  • 配置示例:
schemaName: readwrite_splitting_db
dataSources:
  primary_ds:
    url: jdbc:mysql://localhost:3306/primary_db
    username: root
    password: root
  replica_ds_0:
    url: jdbc:mysql://localhost:3306/replica_db_0
    username: root
    password: root
  replica_ds_1:
    url: jdbc:mysql://localhost:3306/replica_db_1
    username: root
    password: root
rules:
  readwrite_splitting:
    dataSources:
      pr_ds:
        writeDataSourceName: primary_ds
        readDataSourceNames: 
          - replica_ds_0
          - replica_ds_1
        loadBalancerName: round_robin
    loadBalancers:
      round_robin:
        type: ROUND_ROBIN

  • 测试代码: 通过插入数据和查询数据,验证写入主库、读取从库是否生效。

2. 分布式事务

  • 目标:确保跨多个数据库操作的数据一致性。

  • 常用模式

    • XA 事务(强一致性,性能稍低)
    • BASE 模型(最终一致性)
  • 配置示例(XA 事务)

schemaName: transactional_db
dataSources:
  ds_0:
    url: jdbc:mysql://localhost:3306/demo_ds_0
    username: root
    password: root
  ds_1:
    url: jdbc:mysql://localhost:3306/demo_ds_1
    username: root
    password: root
props:
  transaction:
    enabled: true

  • 测试代码: 使用 ShardingSphere 提供的事务管理器实现分布式事务
import org.apache.shardingsphere.transaction.api.TransactionType;
import org.apache.shardingsphere.transaction.api.TransactionTypeHolder;

public class TransactionDemo {
    public static void main(String[] args) throws Exception {
        TransactionTypeHolder.set(TransactionType.XA); // 设置事务类型
        try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/transactional_db", "root", "root")) {
            connection.setAutoCommit(false); // 开启事务

            try (PreparedStatement stmt = connection.prepareStatement("INSERT INTO t_order (order_id, user_id, status) VALUES (?, ?, ?)")) {
                stmt.setInt(1, 1);
                stmt.setInt(2, 1);
                stmt.setString(3, "INIT");
                stmt.executeUpdate();
            }

            try (PreparedStatement stmt = connection.prepareStatement("INSERT INTO t_order (order_id, user_id, status) VALUES (?, ?, ?)")) {
                stmt.setInt(1, 2);
                stmt.setInt(2, 2);
                stmt.setString(3, "INIT");
                stmt.executeUpdate();
            }

            connection.commit(); // 提交事务
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3. 数据加密

  • 目标:对敏感数据(如用户信息)加密存储,并在读取时自动解密
  • 配置示例
schemaName: encrypt_db
dataSources:
  ds:
    url: jdbc:mysql://localhost:3306/demo_ds
    username: root
    password: root
rules:
  encrypt:
    tables:
      t_user:
        columns:
          user_name:
            cipherColumn: user_name_cipher
            encryptorName: aes_encryptor
    encryptors:
      aes_encryptor:
        type: AES
        props:
          aes-key-value: 123456abcde

  • 测试代码: 写入和查询加密字段,验证加密和解密效果。
public class EncryptDemo {
    public static void main(String[] args) throws Exception {
        try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/encrypt_db", "root", "root")) {
            // 插入加密数据
            try (PreparedStatement stmt = connection.prepareStatement("INSERT INTO t_user (user_id, user_name) VALUES (?, ?)")) {
                stmt.setInt(1, 1);
                stmt.setString(2, "Alice");
                stmt.executeUpdate();
            }

            // 查询解密数据
            try (PreparedStatement stmt = connection.prepareStatement("SELECT user_id, user_name FROM t_user")) {
                ResultSet rs = stmt.executeQuery();
                while (rs.next()) {
                    System.out.println("User ID: " + rs.getInt("user_id"));
                    System.out.println("User Name: " + rs.getString("user_name")); // 自动解密
                }
            }
        }
    }
}

二、结合业务场景优化配置

1. 结合业务特点调整分片策略

  • 常用分片策略
    • 范围分片(Range Sharding):适合按时间分表。
    • 哈希分片(Hash Sharding):数据分布更均匀。
    • 复合分片(Composite Sharding):多个字段组合分片。

2. 监控与调试

  • 配置 ShardingSphere 的监控接口,集成 Prometheus 和 Grafana
  • 使用 ShardingSphere 提供的日志调试功能分析 SQL 路由
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值