Sharding-JDBC读写分离

本文内容参考Sharding-JDBC官方文档

规则配置
节点 IP 数据库名
主节点 192.168.3.112 ds_master
从节点 192.168.3.113 ds_slave_0
从节点 192.168.3.114 ds_slave_1
    private static ShardingDataSource getShardingDataSource() {
        DataSourceRule dataSourceRule = new DataSourceRule(createDataSourceMap());
        TableRule orderTableRule = TableRule.builder("t_order").actualTables(Arrays.asList("t_order_0", "t_order_1")).dataSourceRule(dataSourceRule).build();
        TableRule orderItemTableRule = TableRule.builder("t_order_item").actualTables(Arrays.asList("t_order_item_0", "t_order_item_1")).dataSourceRule(dataSourceRule).build();
        ShardingRule shardingRule = ShardingRule.builder().dataSourceRule(dataSourceRule).tableRules(Arrays.asList(orderTableRule, orderItemTableRule))
                .bindingTableRules(Collections.singletonList(new BindingTableRule(Arrays.asList(orderTableRule, orderItemTableRule))))
//                .databaseShardingStrategy(new DatabaseShardingStrategy("user_id", new ModuloDatabaseShardingAlgorithm()))
                .tableShardingStrategy(new TableShardingStrategy("order_id", new ModuloTableShardingAlgorithm())).build();
        return new ShardingDataSource(shardingRule);
    }

    private static Map<String, DataSource> createDataSourceMap() {
        Map<String, DataSource> result = new HashMap<>(2);
        result.put("ds", MasterSlaveDataSourceFactory.createDataSource("ds", createDataSource("192.168.3.112",3306,"ds_master"), createDataSource("192.168.3.113",3306,"ds_slave_0"), createDataSource("192.168.3.114",3306,"ds_slave_1")));
        return result;
    }
    
    private static DataSource createDataSource(final String ip,final Integer port,final String database) {
        BasicDataSource result = new BasicDataSource();
        result.setDriverClassName(com.mysql.jdbc.Driver.class.getName());
        result.setUrl(String.format("jdbc:mysql://%s:%d/%s", ip,port,database));
        result.setUsername("ubuntu");
        result.setPassword("ubuntu");
        return result;
    }
sql导入

将该段sql放入到3个库中执行

master
CREATE SCHEMA IF NOT EXISTS `ds_master`;

CREATE TABLE IF NOT EXISTS `ds_master`.`t_order_0` (`order_id` INT NOT NULL, `user_id` INT NOT NULL, `status` VARCHAR(50), PRIMARY KEY (`order_id`));
CREATE TABLE IF NOT EXISTS `ds_master`.`t_order_1` (`order_id` INT NOT NULL, `user_id` INT NOT NULL, `status` VARCHAR(50), PRIMARY KEY (`order_id`));
CREATE TABLE IF NOT EXISTS `ds_master`.`t_order_item_0` (`item_id` INT NOT NULL, `order_id` INT NOT NULL, `user_id` INT NOT NULL, PRIMARY KEY (`item_id`));
CREATE TABLE IF NOT EXISTS `ds_master`.`t_order_item_1` (`item_id` INT NOT NULL, `order_id` INT NOT NULL, `user_id` INT NOT NULL, PRIMARY KEY (`item_id`));

INSERT INTO `ds_master`.`t_order_0` VALUES (1000, 10, 'INIT_MASTER');
INSERT INTO `ds_master`.`t_order_0` VALUES (1002, 10, 'INIT_MASTER');
INSERT INTO `ds_master`.`t_order_0` VALUES (1004, 10, 'INIT_MASTER');
INSERT INTO `ds_master`.`t_order_0` VALUES (1006, 10, 'INIT_MASTER');
INSERT INTO `ds_master`.`t_order_0` VALUES (1008, 10, 'INIT_MASTER');
INSERT INTO `ds_master`.`t_order_item_0` VALUES (100001, 1000, 10);
INSERT INTO `ds_master`.`t_order_item_0` VALUES (100201, 1002, 10);
INSERT INTO `ds_master`.`t_order_item_0` VALUES (100401, 1004, 10);
INSERT INTO `ds_master`.`t_order_item_0` VALUES (100601, 1006, 10);
INSERT INTO `ds_master`.`t_order_item_0` VALUES (100801, 1008, 10);

INSERT INTO `ds_master`.`t_order_1` VALUES (1001, 10, 'INIT_MASTER');
INSERT INTO `ds_master`.`t_order_1` VALUES (1003, 10, 'INIT_MASTER');
INSERT INTO `ds_master`.`t_order_1` VALUES (1005, 10, 'INIT_MASTER');
INSERT INTO `ds_master`.`t_order_1` VALUES (1007, 10, 'INIT_MASTER');
INSERT INTO `ds_master`.`t_order_1` VALUES (1009, 10, 'INIT_MASTER');
INSERT INTO `ds_master`.`t_order_item_1` VALUES (100101, 1001, 10);
INSERT INTO `ds_master`.`t_order_item_1` VALUES (100301, 1003, 10);
INSERT INTO `ds_master`.`t_order_item_1` VALUES (100501, 1005, 10);
INSERT INTO `ds_master`.`t_order_item_1` VALUES (100701, 1007, 10);
INSERT INTO `ds_master`.`t_order_item_1` VALUES (100901, 1009, 10);
slave1
CREATE SCHEMA IF NOT EXISTS `ds_slave_0`;

CREATE TABLE IF NOT EXISTS `ds_slave_0`.`t_order_0` (`order_id` INT NOT NULL, `user_id` INT NOT NULL, `status` VARCHAR(50), PRIMARY KEY (`order_id`));
CREATE TABLE IF NOT EXISTS `ds_slave_0`.`t_order_1` (`order_id` INT NOT NULL, `user_id` INT NOT NULL, `status` VARCHAR(50), PRIMARY KEY (`order_id`));
CREATE TABLE IF NOT EXISTS `ds_slave_0`.`t_order_item_0` (`item_id` INT NOT NULL, `order_id` INT NOT NULL, `user_id` INT NOT NULL, PRIMARY KEY (`item_id`));
CREATE TABLE IF NOT EXISTS `ds_slave_0`.`t_order_item_1` (`item_id` INT NOT NULL, `order_id` INT NOT NULL, `user_id` INT NOT NULL, PRIMARY KEY (`item_id`));

INSERT INTO `ds_slave_0`.`t_order_0` VALUES (1000, 10, 'INIT_SLAVE_0');
INSERT INTO `ds_slave_0`.`t_order_0` VALUES (1002, 10, 'INIT_SLAVE_0');
INSERT INTO `ds_slave_0`.`t_order_0` VALUES (1004, 10, 'INIT_SLAVE_0');
INSERT INTO `ds_slave_0`.`t_order_0` VALUES (1006, 10, 'INIT_SLAVE_0');
INSERT INTO `ds_slave_0`.`t_order_0` VALUES (1008, 10, 'INIT_SLAVE_0');
INSERT INTO `ds_slave_0`.`t_order_item_0` VALUES (100001, 1000, 10);
INSERT INTO `ds_slave_0`.`t_order_item_0` VALUES (100201, 1002, 10);
INSERT INTO `ds_slave_0`.`t_order_item_0` VALUES (100401, 1004, 10);
INSERT INTO `ds_slave_0`.`t_order_item_0` VALUES (100601, 1006, 10);
INSERT INTO `ds_slave_0`.`t_order_item_0` VALUES (100801, 1008, 10);

INSERT INTO `ds_slave_0`.`t_order_1` VALUES (1001, 10, 'INIT_SLAVE_0');
INSERT INTO `ds_slave_0`.`t_order_1` VALUES (1003, 10, 'INIT_SLAVE_0');
INSERT INTO `ds_slave_0`.`t_order_1` VALUES (1005, 10, 'INIT_SLAVE_0');
INSERT INTO `ds_slave_0`.`t_order_1` VALUES (1007, 10, 'INIT_SLAVE_0');
INSERT INTO `ds_slave_0`.`t_order_1` VALUES (1009, 10, 'INIT_SLAVE_0');
INSERT INTO `ds_slave_0`.`t_order_item_1` VALUES (100101, 1001, 10);
INSERT INTO `ds_slave_0`.`t_order_item_1` VALUES (100301, 1003, 10);
INSERT INTO `ds_slave_0`.`t_order_item_1` VALUES (100501, 1005, 10);
INSERT INTO `ds_slave_0`.`t_order_item_1` VALUES (100701, 1007, 10);
INSERT INTO `ds_slave_0`.`t_order_item_1` VALUES (100901, 1009, 10);
slave2
CREATE SCHEMA IF NOT EXISTS `ds_slave_1`;

CREATE TABLE IF NOT EXISTS `ds_slave_1`.`t_order_0` (`order_id` INT NOT NULL, `user_id` INT NOT NULL, `status` VARCHAR(50), PRIMARY KEY (`order_id`));
CREATE TABLE IF NOT EXISTS `ds_slave_1`.`t_order_1` (`order_id` INT NOT NULL, `user_id` INT NOT NULL, `status` VARCHAR(50), PRIMARY KEY (`order_id`));
CREATE TABLE IF NOT EXISTS `ds_slave_1`.`t_order_item_0` (`item_id` INT NOT NULL, `order_id` INT NOT NULL, `user_id` INT NOT NULL, PRIMARY KEY (`item_id`));
CREATE TABLE IF NOT EXISTS `ds_slave_1`.`t_order_item_1` (`item_id` INT NOT NULL, `order_id` INT NOT NULL, `user_id` INT NOT NULL, PRIMARY KEY (`item_id`));

INSERT INTO `ds_slave_1`.`t_order_0` VALUES (1100, 11, 'INIT_SLAVE_1');
INSERT INTO `ds_slave_1`.`t_order_0` VALUES (1102, 11, 'INIT_SLAVE_1');
INSERT INTO `ds_slave_1`.`t_order_0` VALUES (1104, 11, 'INIT_SLAVE_1');
INSERT INTO `ds_slave_1`.`t_order_0` VALUES (1106, 11, 'INIT_SLAVE_1');
INSERT INTO `ds_slave_1`.`t_order_0` VALUES (1108, 11, 'INIT_SLAVE_1');
INSERT INTO `ds_slave_1`.`t_order_item_0` VALUES (110001, 1100, 11);
INSERT INTO `ds_slave_1`.`t_order_item_0` VALUES (110201, 1102, 11);
INSERT INTO `ds_slave_1`.`t_order_item_0` VALUES (110401, 1104, 11);
INSERT INTO `ds_slave_1`.`t_order_item_0` VALUES (110601, 1106, 11);
INSERT INTO `ds_slave_1`.`t_order_item_0` VALUES (110801, 1108, 11);

INSERT INTO `ds_slave_1`.`t_order_1` VALUES (1101, 11, 'INIT_SLAVE_1');
INSERT INTO `ds_slave_1`.`t_order_1` VALUES (1103, 11, 'INIT_SLAVE_1');
INSERT INTO `ds_slave_1`.`t_order_1` VALUES (1105, 11, 'INIT_SLAVE_1');
INSERT INTO `ds_slave_1`.`t_order_1` VALUES (1107, 11, 'INIT_SLAVE_1');
INSERT INTO `ds_slave_1`.`t_order_1` VALUES (1109, 11, 'INIT_SLAVE_1');
INSERT INTO `ds_slave_1`.`t_order_item_1` VALUES (110101, 1101, 11);
INSERT INTO `ds_slave_1`.`t_order_item_1` VALUES (110301, 1103, 11);
INSERT INTO `ds_slave_1`.`t_order_item_1` VALUES (110501, 1105, 11);
INSERT INTO `ds_slave_1`.`t_order_item_1` VALUES (110701, 1107, 11);
INSERT INTO `ds_slave_1`.`t_order_item_1` VALUES (110901, 1109, 11);
编写查询代码
select()
DataSource dataSource = getShardingDataSource();
printSimpleSelect(dataSource,10,1001);
printSimpleSelect(dataSource,10,1002);
printSimpleSelect(dataSource,10,1003);
printSimpleSelect(dataSource,10,1004);
    private static void printSimpleSelect(final DataSource dataSource,final Integer userId,final Integer orderId) throws SQLException {
        String sql = "SELECT i.*,o.status FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id WHERE o.user_id=? AND o.order_id=?";
        try (
                Connection conn = dataSource.getConnection();
                PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
            preparedStatement.setInt(1, userId);
            preparedStatement.setInt(2, orderId);
            try (ResultSet rs = preparedStatement.executeQuery()) {
                while (rs.next()) {
                    System.out.println(rs.getInt(1)+"\t"+rs.getInt(2)+"\t"+rs.getInt(3)+"\t"+rs.getString(4));
                }
            }
        }
    }
select.png
gourpby()
DataSource dataSource = getShardingDataSource();
printGroupBy(dataSource);
    private static void printGroupBy(final DataSource dataSource) throws SQLException {
        String sql = "SELECT o.user_id, COUNT(*) FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id GROUP BY o.user_id";
        try (
                Connection conn = dataSource.getConnection();
                PreparedStatement preparedStatement = conn.prepareStatement(sql)
                ) {
            ResultSet rs = preparedStatement.executeQuery();
            while (rs.next()) {
                System.out.println("user_id: " + rs.getInt(1) + ", count: " + rs.getInt(2));
            }
        }
    }
groupby.png
hintSimpleSelect()
DataSource dataSource = getShardingDataSource();
printHintSimpleSelect(dataSource,10,1001);
printHintSimpleSelect(dataSource,10,1002);
printHintSimpleSelect(dataSource,10,1003);
printHintSimpleSelect(dataSource,10,1004);
    private static void printHintSimpleSelect(final DataSource dataSource,final Integer userId,final Integer orderId) throws SQLException {
        String sql = "SELECT i.*,o.status FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id";
        try (
                HintManager hintManager = HintManager.getInstance();
                Connection conn = dataSource.getConnection();
                PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
            hintManager.addDatabaseShardingValue("t_order", "user_id", userId);
            hintManager.addTableShardingValue("t_order", "order_id", orderId);
            try (ResultSet rs = preparedStatement.executeQuery()) {
                while (rs.next()) {
                    System.out.println(rs.getInt(1)+"\t"+rs.getInt(2)+"\t"+rs.getInt(3)+"\t"+rs.getString(4));
                }
            }
        }
    }
hint_select.png
insert
Main.Order order = new Main.Order();
Main.OrderItem order_item = new Main.OrderItem();
Integer orderId  = 2000;
Integer userId = 20;
Integer itemId = 200020;
order.setOrder_id(orderId);
order.setUser_id(userId);
order.setStatus("insert");
        
order_item.setItem_id(itemId);
order_item.setOrder_id(orderId);
order_item.setUser_id(userId);
insertData(dataSource, order, order_item);
    private static void insertData(final DataSource dataSource,final Order order,final OrderItem order_item){
        String sql_order = "INSERT INTO `t_order` (`order_id`, `user_id`, `status`) VALUES (?, ?, ?)";
        String sql_order_item = "INSERT INTO `t_order_item` (`item_id`, `order_id`, `user_id`) VALUES (?, ?, ?)";
        try (Connection connection = dataSource.getConnection()) {
            PreparedStatement preparedStatement = connection.prepareStatement(sql_order);
            preparedStatement.setInt(1, order.getOrder_id());
            preparedStatement.setInt(2, order.getUser_id());
            preparedStatement.setString(3, order.getStatus());
            preparedStatement.execute();
            preparedStatement.close();

            preparedStatement = connection.prepareStatement( sql_order_item);
            preparedStatement.setInt(1, order_item.getItem_id());
            preparedStatement.setInt(2, order_item.getOrder_id());
            preparedStatement.setInt(3, order_item.getUser_id());
            preparedStatement.execute();
            preparedStatement.close();
            // CHECKSTYLE:OFF
        } catch (final Exception ex) {
            // CHECKSTYLE:ON
            ex.printStackTrace();
        }
    }
insert.png

只有在master节点的数据库中插入了数据,slave节点的数据需要数据库同步配置。

官方文档这样说的
支持项
1.提供了一主多从的读写分离配置,可配合分库分表使用。
2.同一线程且同一数据库连接内,如有写入操作,以后的读操作均从主库读取,用于保证数据一致性。
3.Spring命名空间。
4.基于Hint的强制主库路由。
不支持范围
1.主库和从库的数据同步。
2.主库和从库的数据同步延迟导致的数据不一致。
3.主库双写或多写。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容