前言
本篇是建立在上篇的ShardingSphere Jdbc 读写分离的基础上做出改动
提前在数据库创建t_user_0、t_user_1表。
配置
application.yml
spring:
shardingsphere:
datasource:
names: master-write,slave-read
master-write:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://192.168.126.156:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: 123456
slave-read:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://192.168.126.156:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: 123456
rules:
readwrite-splitting:
load-balancers:
ms:
type: ROUND_ROBIN
props:
workId: 1
data-sources:
ms:
type: Static
load-balancer-name: round-robin
props:
write-data-source-name: master-write
read-data-source-names: slave-read
sharding:
sharding-algorithms:
table-inline:
type: INLINE
props:
algorithm-expression: t_user_$->{id % 2}
tables:
t_user:
actual-data-nodes: master-write.t_user_$->{0..1}
table-strategy:
standard:
sharding-column: id
sharding-algorithm-name: table-inline
props:
sql-show: true
测试类
import com.terry.App;
import lombok.extern.java.Log;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import java.util.Map;
@SpringBootTest(classes = App.class)
@Log
public class TestShardingSphereJdbc {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void testQuery(){
List<Map<String, Object>> maps = jdbcTemplate.queryForList(" SELECT * FROM t_user ");
log.info("数据库数据:" + maps);
}
@Test
public void testInsert(){
jdbcTemplate.update("INSERT INTO t_user(id, name) VALUES(?, ?)", Arrays.asList(4, "李四").toArray());
}
}
运行打印输出:
testInsert:
Actual SQL: master-write ::: INSERT INTO t_user_0(id, name) VALUES(?, ?) ::: [4, 李四]
testQuery:
Actual SQL: master-write ::: SELECT * FROM t_user_0 WHERE id = 4
数据库数据:[{id=4, name=李四}]
根据分表策略来插入和查询。
|