行业知识
shardingsphere集成springboot 【水平分库】
2026-10-20 23:59:52
来源:互联网转载
在不同���数据节点上创建不同名称的数据ds1,ds2
()在两个数据库上创建相同的表t_order_1,t_order_2
分片规则,按照customer_id的奇偶性来进行分库,然后按照id的奇偶性进行分表
()修改配置文件
引入依赖
org.apache.shardingsphere sharding-jdbc-spring-boot-starter 4.1.1 org.apache.shardingsphere sharding-jdbc-spring-namespace 4.1.1
修改yaml配置文件
spring: shardingsphere: datasource: #数据源配置 names: ds1,ds2 ds1: #数据源0 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/ds1?serverTimezone=UTC&useSSL=false username: root password: wsrbb ds2: #数据源1 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/ds2?serverTimezone=UTC&useSSL=false username: root password: wsrbb sharding: default-database-strategy: inline: sharding-column: customer_id algorithm-expression: ds${customer_id % 2 +1} tables: t_order: actual-data-nodes: ds${1..2}.t_order_${1..2} key-generator: column: id type: SNOWFLAKE props: worker-id: 123 max-vibration-offset: 3 table-strategy: inline: sharding-column: id algorithm-expression: t_order_${id % 2 +1} 修改mapper类
@Repository @Mapper public interface OrderMapper { @Insert("insert into t_order(order_type,customer_id,amount) values(#{orderType},#{customerId},#{amount})") public void insert(Order orders); @Select("select * from t_order where id = #{id}") @Results({ @Result(property = "id",column = "id"), @Result(property = "orderType",column = "order_type"), @Result(property = "customerId",column = "customer_id"), @Result(property = "amount",column = "amount") }) public Order selectOne(Integer id);} 编写测试类
@Resource private OrderMapper orderMapper; @Test public void addOrders(){ for (int i = 1; i Order orders = new Order(); //orders.setId(i); orders.setCustomerId(new Random().nextInt(10)); orders.setOrderType(i); orders.setAmount(1000.0*i); orderMapper.insert(orders); } } @Test public void queryOrders(){ Order orders = orderMapper.selectOne(1); System.out.println(orders); }
上一篇:揭秘分分彩对码计算技巧,警惕背后的法律风险与犯罪风险!
下一篇:为什么找不到视频?