数据库技术javahello world

Sharing-JDBC入门

2016-10-31  本文已影响4832人  AnyL8023

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

因为第一次接触数据库中间件,主要看了一下Sharding-JDBC和MyCat,感觉数据库中间件,在系统中主要起到一个路由分配的作用,跟一般用的路由器的相似。需要通过一系列的配置和规则来规定,数据查询和存储的位置。
与MyCat不同,Sharding-JDBC不需要安装客户端。

Sharding-JDBC系统架构图:


引入maven依赖
<dependency>
    <groupId>com.dangdang</groupId>
    <artifactId>sharding-jdbc-core</artifactId>
    <version>${latest.release.version}</version>
</dependency>
规则配置
    <bean id="dbtbl_0" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://192.168.3.112:3306/dbtb"/>
        <property name="username" value="ubuntu"/>
        <property name="password" value="ubuntu"/>
    </bean>

    <bean id="dbtbl_1" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://192.168.3.113:3306/dbtb"/>
        <property name="username" value="ubuntu"/>
        <property name="password" value="ubuntu"/>
    </bean>
    
    <bean id="dbtbl_2" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://192.168.3.114:3306/dbtb"/>
        <property name="username" value="ubuntu"/>
        <property name="password" value="ubuntu"/>
    </bean>

    <rdb:strategy id="databaseStrategy" sharding-columns="user_id" algorithm-expression="dbtbl_${user_id.longValue() % 3}"/>
    <rdb:strategy id="orderTableStrategy" sharding-columns="order_id" algorithm-expression="t_order_${order_id.longValue() % 2}"/>
    <rdb:strategy id="orderItemTableStrategy" sharding-columns="order_id" algorithm-class="com.dangdang.ddframe.rdb.sharding.example.config.spring.algorithm.SingleKeyModuloTableShardingAlgorithm"/>

    <rdb:data-source id="shardingDataSource">
        <rdb:sharding-rule data-sources="dbtbl_0,dbtbl_1,dbtbl_2">
            <rdb:table-rules>
                <rdb:table-rule logic-table="t_order" actual-tables="t_order_${0..1}" database-strategy="databaseStrategy" table-strategy="orderTableStrategy"/>
                <rdb:table-rule logic-table="t_order_item" actual-tables="t_order_item_0,t_order_item_1" database-strategy="databaseStrategy" table-strategy="orderItemTableStrategy"/>
            </rdb:table-rules>
        </rdb:sharding-rule>
    </rdb:data-source>
sql导入

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

CREATE SCHEMA IF NOT EXISTS `dbtb`;

CREATE TABLE IF NOT EXISTS `dbtb`.`t_order_0` (`order_id` INT NOT NULL, `user_id` INT NOT NULL, `status` VARCHAR(10) NULL, PRIMARY KEY (`order_id`));
CREATE TABLE IF NOT EXISTS `dbtb`.`t_order_1` (`order_id` INT NOT NULL, `user_id` INT NOT NULL, `status` VARCHAR(10) NULL, PRIMARY KEY (`order_id`));
CREATE TABLE IF NOT EXISTS `dbtb`.`t_order_item_0` (`order_item_id` INT NOT NULL, `order_id` INT NOT NULL, `user_id` INT NOT NULL, `status` VARCHAR(10) NULL, PRIMARY KEY (`order_item_id`));
CREATE TABLE IF NOT EXISTS `dbtb`.`t_order_item_1` (`order_item_id` INT NOT NULL, `order_id` INT NOT NULL, `user_id` INT NOT NULL, `status` VARCHAR(10) NULL, PRIMARY KEY (`order_item_id`));

insert()

    @Override
    public void insert() {
        String orderSql = "INSERT INTO `t_order` (`order_id`, `user_id`, `status`) VALUES (?, ?, ?)";
        String orderItemSql = "INSERT INTO `t_order_item` (`order_item_id`, `order_id`, `user_id`, `status`) VALUES (?, ?, ?, ?)";
        for (int orderId = 1; orderId <= 2; orderId++) {
            for (int userId = 1; userId <= 3; userId++) {
                try (Connection connection = shardingDataSource.getConnection()) {
                    PreparedStatement preparedStatement = connection.prepareStatement(orderSql);
                    preparedStatement.setInt(1, orderId);
                    preparedStatement.setInt(2, userId);
                    preparedStatement.setString(3, "insert");
                    preparedStatement.execute();
                    preparedStatement.close();

                    preparedStatement = connection.prepareStatement(orderItemSql);
                    int orderItemId = orderId + 4;
                    preparedStatement.setInt(1, orderItemId);
                    preparedStatement.setInt(2, orderId);
                    preparedStatement.setInt(3, userId);
                    preparedStatement.setString(4, "insert");
                    preparedStatement.execute();
                    preparedStatement.close();
                    // CHECKSTYLE:OFF
                } catch (final Exception ex) {
                    // CHECKSTYLE:ON
                    ex.printStackTrace();
                }
            }
        }
    }

selectAll()

    @Override
    public void selectAll() {
        String sql = "SELECT i.* FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id";
        try (Connection conn = shardingDataSource.getConnection();
                PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
            try (ResultSet rs = preparedStatement.executeQuery()) {
                while (rs.next()) {
                    System.out.println("orderItemId:" + rs.getInt(1) + ",orderId:" + rs.getInt(2) + ",userId:"
                            + rs.getInt(3) + ",status:" + rs.getString(4));
                }
            }
            // CHECKSTYLE:OFF
        } catch (final Exception ex) {
            // CHECKSTYLE:ON
            ex.printStackTrace();
        }
    }
selectAll.png

count()

    @Override
    public void count() {
        String sql = "SELECT count(1) FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id";
        try (Connection conn = shardingDataSource.getConnection();
                PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
            try (ResultSet rs = preparedStatement.executeQuery()) {
                while (rs.next()) {
                    System.out.println("count :" + rs.getInt(1));
                }
            }
            // CHECKSTYLE:OFF
        } catch (final Exception ex) {
            // CHECKSTYLE:ON
            ex.printStackTrace();
        }
    }

count.png

orderby()

    @Override
    public void orderby() {
        String sql = "SELECT i.* FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id order by o.user_id asc,i.order_id asc";
        try (Connection conn = shardingDataSource.getConnection();
                PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
            try (ResultSet rs = preparedStatement.executeQuery()) {
                while (rs.next()) {
                    System.out.println("orderItemId:" + rs.getInt(1) + ",orderId:" + rs.getInt(2) + ",userId:"
                            + rs.getInt(3) + ",status:" + rs.getString(4));
                }
            }
            // CHECKSTYLE:OFF
        } catch (final Exception ex) {
            // CHECKSTYLE:ON
            ex.printStackTrace();
        }
    }
orderby.png

groupby()

    @Override
    public void groupby() {
        String sql = "SELECT o.user_id,count(o.user_id) FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id group by o.user_id";
        try (Connection conn = shardingDataSource.getConnection();
                PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
            try (ResultSet rs = preparedStatement.executeQuery()) {
                while (rs.next()) {
                    System.out.println("userId:" + rs.getInt(1) + ",count:" + rs.getInt(2));
                }
            }
            // CHECKSTYLE:OFF
        } catch (final Exception ex) {
            // CHECKSTYLE:ON
            ex.printStackTrace();
        }
    }
groupby.png

limit()

    @Override
    public void limit() {
        String sql = "SELECT i.* FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id order by o.user_id asc,i.order_id asc limit 1,3";
        try (Connection conn = shardingDataSource.getConnection();
                PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
            try (ResultSet rs = preparedStatement.executeQuery()) {
                while (rs.next()) {
                    System.out.println("orderItemId:" + rs.getInt(1) + ",orderId:" + rs.getInt(2) + ",userId:"
                            + rs.getInt(3) + ",status:" + rs.getString(4));
                }
            }
            // CHECKSTYLE:OFF
        } catch (final Exception ex) {
            // CHECKSTYLE:ON
            ex.printStackTrace();
        }
    }
limit.png

delete()

    @Override
    public void delete() {
        String orderSql = "DELETE FROM `t_order`";
        String orderItemSql = "DELETE FROM `t_order_item`";
        try (Connection connection = shardingDataSource.getConnection()) {
            PreparedStatement preparedStatement = connection.prepareStatement(orderSql);
            preparedStatement.execute();
            preparedStatement.close();
            preparedStatement = connection.prepareStatement(orderItemSql);
            preparedStatement.execute();
            preparedStatement.close();
            // CHECKSTYLE:OFF
        } catch (final Exception ex) {
            // CHECKSTYLE:ON
            ex.printStackTrace();
        }
    }

以上根据Sharding-JDBC官方demo修改,详见官方demo。

上一篇下一篇

猜你喜欢

热点阅读