shardingsphere集成springboot 【水平分库】
在不同的数据节点上创建不同名称的数据ds1,ds2
在两个数据库上创建相同的表t_order_1,t_order_2
分片规则,按照customer_id的奇偶性来进行分库,然后按照id的奇偶性进行分表
修改配置文件
引入依赖
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-namespace</artifactId>
<version>4.1.1</version>
</dependency>
修改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 <=10 ; 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);
}
原文地址:https://blog.csdn.net/qq_28527383/article/details/136352071
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!