目录
1 Maven依赖
2 配置文件
3 Controller
4 Service
5 Model
6 Mapper
7 运行结果
ShardingSphere是一款开源的支持分库分表的数据库中间件,其由三部分组成:
本文对Sharding-JDBC做一个简单的模拟分库分表的使用,完整的使用请参看官方文档。
这里模拟两个数据库test1和test2,分别有两张t_order和两张t_order_item表,如下所示:
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.2.6.RELEASE
com.hys
sharding-jdbc-demo
0.0.1-SNAPSHOT
sharding-jdbc-demo
1.8
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.2
mysql
mysql-connector-java
runtime
org.apache.shardingsphere
sharding-jdbc-spring-boot-starter
4.0.1
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-maven-plugin
#配置ds0和ds1两个数据源
spring.shardingsphere.datasource.names=ds0,ds1
#ds0配置
spring.shardingsphere.datasource.ds0.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds0.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds0.jdbc-url=jdbc:mysql://127.0.0.1:3306/test1?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=UTF-8
spring.shardingsphere.datasource.ds0.username=root
spring.shardingsphere.datasource.ds0.password=root
#ds1配置
spring.shardingsphere.datasource.ds1.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds1.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds1.jdbc-url=jdbc:mysql://127.0.0.1:3306/test2?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=UTF-8
spring.shardingsphere.datasource.ds1.username=root
spring.shardingsphere.datasource.ds1.password=root
#分库策略,根据id取模确定数据进哪个数据库
spring.shardingsphere.sharding.default-database-strategy.inline.sharding-column=user_id
spring.shardingsphere.sharding.default-database-strategy.inline.algorithm-expression=ds$->{user_id % 2}
#绑定表
spring.shardingsphere.sharding.binding-tables=t_order,t_order_item
#具体分表策略
#节点ds0.t_order_0,ds0.t_order_1,ds1.t_order_0,ds1.t_order_1
spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds$->{0..1}.t_order_$->{0..1}
#分表字段id
spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.sharding-column=order_id
#分表策略,根据id取模,确定数据最终落在那个表中
spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.algorithm-expression=t_order_$->{order_id % 2}
#使用SNOWFLAKE算法生成主键
spring.shardingsphere.sharding.tables.t_order.key-generator.column=order_id
spring.shardingsphere.sharding.tables.t_order.key-generator.type=SNOWFLAKE
#节点ds0.t_order_item_0,ds0.t_order_item_1,ds1.t_order_item_0,ds1.t_order_item_1
spring.shardingsphere.sharding.tables.t_order_item.actual-data-nodes=ds$->{0..1}.t_order_item_$->{0..1}
#分表字段id
spring.shardingsphere.sharding.tables.t_order_item.table-strategy.inline.sharding-column=order_id
#分表策略,根据id取模,确定数据最终落在那个表中
spring.shardingsphere.sharding.tables.t_order_item.table-strategy.inline.algorithm-expression=t_order_item_$->{order_id % 2}
#使用SNOWFLAKE算法生成主键
spring.shardingsphere.sharding.tables.t_order_item.key-generator.column=order_item_id
spring.shardingsphere.sharding.tables.t_order_item.key-generator.type=SNOWFLAKE
import com.hys.shardingjdbc.demo.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 订单
*
* @author Robert Hou
* @date 2020年05月01日 14:51
**/
@RestController
public class OrderController {
@Autowired
private OrderService orderService;
@GetMapping("confirm_order")
public String confirmOrder(Integer sequenceId) {
long id = orderService.confirmOrder(sequenceId);
return "创建订单成功:订单ID = " + id;
}
}
/**
* 订单
*
* @author Robert Hou
* @date 2020年05月01日 14:48
**/
public interface OrderService {
long confirmOrder(int sequenceId);
}
import com.hys.shardingjdbc.demo.mapper.OrderItemMapper;
import com.hys.shardingjdbc.demo.mapper.OrderMapper;
import com.hys.shardingjdbc.demo.model.Order;
import com.hys.shardingjdbc.demo.model.OrderItem;
import com.hys.shardingjdbc.demo.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.SQLException;
/**
* 订单
*
* @author Robert Hou
* @date 2020年05月01日 14:48
**/
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private OrderItemMapper orderItemMapper;
@Override
public long confirmOrder(int sequenceId) {
//创建订单
Order order = new Order();
order.setAddressId(sequenceId);
order.setUserId(sequenceId);
order.setStatus("创建订单");
orderMapper.insert(order);
//订单对应产品
OrderItem item = new OrderItem();
item.setOrderId(order.getOrderId());
item.setUserId(sequenceId);
item.setOrderItemId(sequenceId);
item.setStatus("创建订单");
orderItemMapper.insert(item);
return order.getOrderId();
}
}
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 订单
*
* @author Robert Hou
* @date 2020年05月01日 14:42
**/
@Data
@NoArgsConstructor
public class Order implements Serializable {
private static final long serialVersionUID = -3963571151434932747L;
private long orderId;
private int userId;
private long addressId;
private String status;
}
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 订单项
*
* @author Robert Hou
* @date 2020年05月01日 14:46
**/
@Data
@NoArgsConstructor
public class OrderItem implements Serializable {
private static final long serialVersionUID = -7096145519089736408L;
private long orderItemId;
private long orderId;
private int userId;
private String status;
}
import com.hys.shardingjdbc.demo.model.Order;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import java.sql.SQLException;
/**
* 订单
*
* @author Robert Hou
* @date 2020年05月01日 14:41
**/
@Mapper
public interface OrderMapper {
@Options(useGeneratedKeys = true, keyProperty = "orderId", keyColumn = "order_id")
@Insert("INSERT INTO t_order (user_id, address_id, status) VALUES (#{userId,jdbcType=INTEGER}, #{addressId,jdbcType=BIGINT}, #{status,jdbcType=VARCHAR})")
long insert(Order order);
}
import com.hys.shardingjdbc.demo.model.OrderItem;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import java.sql.SQLException;
/**
* 订单项
*
* @author Robert Hou
* @date 2020年05月01日 14:46
**/
@Mapper
public interface OrderItemMapper {
@Options(useGeneratedKeys = true, keyProperty = "orderItemId", keyColumn = "order_item_id")
@Insert("INSERT INTO t_order_item (order_id, user_id, status) VALUES (#{orderId,jdbcType=INTEGER}, #{userId,jdbcType=INTEGER}, #{status,jdbcType=VARCHAR})")
long insert(OrderItem order);
}
当启动完项目后,可以在日志中看到打印了分库分表的信息:
bindingTables:
- t_order
- t_order_item
defaultDatabaseStrategy:
inline:
algorithmExpression: ds$->{user_id % 2}
shardingColumn: user_id
tables:
t_order:
actualDataNodes: ds$->{0..1}.t_order_$->{0..1}
keyGenerator:
column: order_id
type: SNOWFLAKE
logicTable: t_order
tableStrategy:
inline:
algorithmExpression: t_order_$->{order_id % 2}
shardingColumn: order_id
t_order_item:
actualDataNodes: ds$->{0..1}.t_order_item_$->{0..1}
keyGenerator:
column: order_item_id
type: SNOWFLAKE
logicTable: t_order_item
tableStrategy:
inline:
algorithmExpression: t_order_item_$->{order_id % 2}
shardingColumn: order_id
接着输入http://localhost:8080/confirm_order?sequenceId=1和http://localhost:8080/confirm_order?sequenceId=2,随后查看数据库,可以看到分库分表成功: