欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Mysql使用Sharding-JDBC配置教程

 更新時(shí)間:2025年02月18日 09:55:59   作者:趙廣陸  
文章介紹了如何使用Sharding-JDBC對(duì)訂單表進(jìn)行水平分表,并通過(guò)配置分片規(guī)則、數(shù)據(jù)操作和測(cè)試驗(yàn)證了分表的實(shí)現(xiàn),同時(shí),文章還討論了Sharding-JDBC的多種集成方式和4種分片策略的實(shí)現(xiàn)方法,包括標(biāo)準(zhǔn)分片策略、復(fù)合分片策略、行表達(dá)式分片策略和Hint分片策略

1 需求說(shuō)明

使用Sharding-JDBC完成對(duì)訂單表的水平分表,通過(guò)快速入門程序的開(kāi)發(fā),快速體驗(yàn)Sharding-JDBC的使用方法。

人工創(chuàng)建兩張表,t_order_1和t_order_2,這兩張表是訂單表拆分后的表,通過(guò)Sharding-Jdbc向訂單表插入數(shù)據(jù),按照一定的分片規(guī)則,主鍵為偶數(shù)的進(jìn)入t_order_1,另一部分?jǐn)?shù)據(jù)進(jìn)入t_order_2,通過(guò)Sharding-Jdbc 查詢數(shù)據(jù),根據(jù) SQL語(yǔ)句的內(nèi)容從t_order_1或t_order_2查詢數(shù)據(jù)。

2 環(huán)境搭建

2.1 環(huán)境說(shuō)明

  • 操作系統(tǒng): Win10
  • 數(shù)據(jù)庫(kù): MySQL-5.7.25
  • JDK :64位 jdk1.8.0_201
  • 應(yīng)用框架: spring-boot-2.1.3.RELEASE,Mybatis3.5.0
  • Sharding-JDBC :sharding-jdbc-spring-boot-starter-4.0.0-RC1

2.2 創(chuàng)建數(shù)據(jù)庫(kù)

創(chuàng)建訂單庫(kù) order_db

CREATE DATABASE `order_db` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';

在order_db中創(chuàng)建t_order_1、t_order_2表

DROP TABLE IF EXISTS `t_order_1`;
CREATE TABLE `t_order_1`  (
  `order_id` bigint(20) NOT NULL COMMENT '訂單id',
  `price` decimal(10, 2) NOT NULL COMMENT '訂單價(jià)格',
  `user_id` bigint(20) NOT NULL COMMENT '下單用戶id',
  `status` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '訂單狀態(tài)',
  PRIMARY KEY (`order_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
DROP TABLE IF EXISTS `t_order_2`;
CREATE TABLE `t_order_2`  (
  `order_id` bigint(20) NOT NULL COMMENT '訂單id',
  `price` decimal(10, 2) NOT NULL COMMENT '訂單價(jià)格',
  `user_id` bigint(20) NOT NULL COMMENT '下單用戶id',
  `status` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '訂單狀態(tài)',
  PRIMARY KEY (`order_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

2.3.引入maven依賴

引入 sharding-jdbc和SpringBoot整合的Jar包:

<dependency>
  <groupId>org.apache.shardingsphere</groupId>
  <artifactId>sharding‐jdbc‐spring‐boot‐starter</artifactId>
  <version>4.0.0‐RC1</version>
</dependency>

具體spring boot相關(guān)依賴及配置請(qǐng)參考資料中dbsharding/sharding-jdbc-simple工程,本指引只說(shuō)明與Sharding-JDBC相關(guān)的內(nèi)容。

3 編寫程序

3.1 分片規(guī)則配置

分片規(guī)則配置是sharding-jdbc進(jìn)行對(duì)分庫(kù)分表操作的重要依據(jù),配置內(nèi)容包括:數(shù)據(jù)源、主鍵生成策略、分片策略等。

在application.properties中配置

server.port=56081
spring.application.name = sharding‐jdbc‐simple‐demo
server.servlet.context‐path = /sharding‐jdbc‐simple‐demo
spring.http.encoding.enabled = true
spring.http.encoding.charset = UTF‐8
spring.http.encoding.force = true
spring.main.allow‐bean‐definition‐overriding = true
mybatis.configuration.map‐underscore‐to‐camel‐case = true
# 以下是分片規(guī)則配置
# 定義數(shù)據(jù)源
spring.shardingsphere.datasource.names = m1
spring.shardingsphere.datasource.m1.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m1.driver‐class‐name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.m1.url = jdbc:mysql://localhost:3306/order_db?useUnicode=true
spring.shardingsphere.datasource.m1.username = root
spring.shardingsphere.datasource.m1.password = root
# 指定t_order表的數(shù)據(jù)分布情況,配置數(shù)據(jù)節(jié)點(diǎn)
spring.shardingsphere.sharding.tables.t_order.actual‐data‐nodes = m1.t_order_$‐>{1..2}
# 指定t_order表的主鍵生成策略為SNOWFLAKE
spring.shardingsphere.sharding.tables.t_order.key‐generator.column=order_id
spring.shardingsphere.sharding.tables.t_order.key‐generator.type=SNOWFLAKE
# 指定t_order表的分片策略,分片策略包括分片鍵和分片算法
spring.shardingsphere.sharding.tables.t_order.table‐strategy.inline.sharding‐column = order_id
spring.shardingsphere.sharding.tables.t_order.table‐strategy.inline.algorithm‐expression =
t_order_$‐>{order_id % 2 + 1}
       
# 打開(kāi)sql輸出日志
spring.shardingsphere.props.sql.show = true
swagger.enable = true
logging.level.root = info
logging.level.org.springframework.web = info
logging.level.com.itheima.dbsharding  = debug
logging.level.druid.sql = debug
  • 首先定義數(shù)據(jù)源m1,并對(duì)m1進(jìn)行實(shí)際的參數(shù)配置。
  • 指定t_order表的數(shù)據(jù)分布情況,他分布在m1.t_order_1,m1.t_order_2
  • 指定t_order表的主鍵生成策略為SNOWFLAKE,SNOWFLAKE是一種分布式自增算法,保證id全局唯一
  • 定義t_order分片策略,order_id為偶數(shù)的數(shù)據(jù)落在t_order_1,為奇數(shù)的落在t_order_2,分表策略的表達(dá)式為t_order_$->{order_id % 2 + 1}

3.2. 數(shù)據(jù)操作

@Mapper
@Component
public interface OrderDao {
    /**
     * 新增訂單
     * @param price 訂單價(jià)格
     * @param userId 用戶id
     * @param status 訂單狀態(tài)
     * @return
     */
    @Insert("insert into t_order(price,user_id,status) value(#{price},#{userId},#{status})")
    int insertOrder(@Param("price") BigDecimal price, @Param("userId")Long userId,
@Param("status")String status);
    /**
     * 根據(jù)id列表查詢多個(gè)訂單
     * @param orderIds 訂單id列表
     * @return
     */
    @Select({"<script>" +
            "select " +
            " * " +
            " from t_order t" +
            " where t.order_id in " +
            "<foreach collection='orderIds' item='id' open='(' separator=',' close=')'>" +
            " #{id} " +
            "</foreach>"+
            "</script>"})
    List<Map> selectOrderbyIds(@Param("orderIds")List<Long> orderIds);
}

3.3 測(cè)試

編寫單元測(cè)試:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ShardingJdbcSimpleDemoBootstrap.class})
public class OrderDaoTest {
    @Autowired
    private OrderDao orderDao;
    @Test
    public void testInsertOrder(){
        for (int i = 0 ; i<10; i++){
            orderDao.insertOrder(new BigDecimal((i+1)*5),1L,"WAIT_PAY");
        }
    }
     @Test
    public void testSelectOrderbyIds(){
        List<Long> ids = new ArrayList<>();
        ids.add(373771636085620736L);
        ids.add(373771635804602369L);
        List<Map> maps = orderDao.selectOrderbyIds(ids);
        System.out.println(maps);
    }
}

執(zhí)行 testInsertOrder:

通過(guò)日志可以發(fā)現(xiàn)order_id為奇數(shù)的被插入到t_order_2表,為偶數(shù)的被插入到t_order_1表,達(dá)到預(yù)期目標(biāo)。

執(zhí)行testSelectOrderbyIds:

通過(guò)日志可以發(fā)現(xiàn),根據(jù)傳入order_id的奇偶不同,sharding-jdbc分別去不同的表檢索數(shù)據(jù),達(dá)到預(yù)期目標(biāo)。

4 流程分析

通過(guò)日志分析,Sharding-JDBC在拿到用戶要執(zhí)行的sql之后干了哪些事兒:

(1)解析sql,獲取片鍵值,在本例中是order_id

(2)Sharding-JDBC通過(guò)規(guī)則配置 t_order_$->{order_id % 2 + 1},知道了當(dāng)order_id為偶數(shù)時(shí),應(yīng)該往t_order_1表插數(shù)據(jù),為奇數(shù)時(shí),往t_order_2插數(shù)據(jù)。

(3)于是Sharding-JDBC根據(jù)order_id的值改寫sql語(yǔ)句,改寫后的SQL語(yǔ)句是真實(shí)所要執(zhí)行的SQL語(yǔ)句。

(4)執(zhí)行改寫后的真實(shí)sql語(yǔ)句

(5)將所有真正執(zhí)行sql的結(jié)果進(jìn)行匯總合并,返回。

5 其他集成方式

Sharding-JDBC不僅可以與spring boot良好集成,它還支持其他配置方式,共支持以下四種集成方式。

5.1 Spring Boot Yaml 配置

定義application.yml,內(nèi)容如下:

 server:
  port: 56081
  servlet:
    context‐path: /sharding‐jdbc‐simple‐demo
spring:
  application:
    name: sharding‐jdbc‐simple‐demo
  http:
    encoding:
      enabled: true
      charset: utf‐8
      force: true
  main:
    allow‐bean‐definition‐overriding: true
  shardingsphere:
    datasource:
      names: m1
      m1:
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/order_db?useUnicode=true
        username: root
        password: mysql
    sharding:
      tables:
        t_order:
          actualDataNodes: m1.t_order_$‐>{1..2}
          tableStrategy:
            inline:
              shardingColumn: order_id
              algorithmExpression: t_order_$‐>{order_id % 2 + 1}
          keyGenerator:
            type: SNOWFLAKE
            column: order_id
    props:
      sql:
        show: true
mybatis:
  configuration:
    map‐underscore‐to‐camel‐case: true
swagger:
  enable: true
logging:
  level:
    root: info
    org.springframework.web: info
    com.itheima.dbsharding: debug
    druid.sql: debug

如果使用 application.yml則需要屏蔽原來(lái)的application.properties文件。

5.2 Java 配置

添加配置類:

@Configuration
public class ShardingJdbcConfig {
    // 定義數(shù)據(jù)源
    Map<String, DataSource> createDataSourceMap() {
        DruidDataSource dataSource1 = new DruidDataSource();
        dataSource1.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource1.setUrl("jdbc:mysql://localhost:3306/order_db?useUnicode=true");
        dataSource1.setUsername("root");
        dataSource1.setPassword("root");
        Map<String, DataSource> result = new HashMap<>();
        result.put("m1", dataSource1);
        return result;
    }
    // 定義主鍵生成策略
    private static KeyGeneratorConfiguration getKeyGeneratorConfiguration() {
        KeyGeneratorConfiguration result = new
KeyGeneratorConfiguration("SNOWFLAKE","order_id");
        return result;
    }
    // 定義t_order表的分片策略
    TableRuleConfiguration getOrderTableRuleConfiguration() {
        TableRuleConfiguration result = new TableRuleConfiguration("t_order","m1.t_order_$‐>
{1..2}");
        result.setTableShardingStrategyConfig(new
InlineShardingStrategyConfiguration("order_id", "t_order_$‐>{order_id % 2 + 1}"));
        result.setKeyGeneratorConfig(getKeyGeneratorConfiguration());
        return result;
    }
    // 定義sharding‐Jdbc數(shù)據(jù)源
    @Bean
    DataSource getShardingDataSource() throws SQLException {
        ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
        shardingRuleConfig.getTableRuleConfigs().add(getOrderTableRuleConfiguration());
        //spring.shardingsphere.props.sql.show = true
        Properties properties = new Properties();
        properties.put("sql.show","true");
        return ShardingDataSourceFactory.createDataSource(createDataSourceMap(),
        shardingRuleConfig,properties);
    }
}

由于采用了配置類所以需要屏蔽原來(lái) application.properties文件中spring.shardingsphere開(kāi)頭的配置信息。

還需要在SpringBoot啟動(dòng)類中屏蔽使用spring.shardingsphere配置項(xiàng)的類:

@SpringBootApplication(exclude = {SpringBootConfiguration.class})
public class ShardingJdbcSimpleDemoBootstrap {....}

5.3 Spring Boot properties配置

此方式同快速入門程序。

# 定義數(shù)據(jù)源
spring.shardingsphere.datasource.names = m1
spring.shardingsphere.datasource.m1.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m1.driver‐class‐name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.m1.url = jdbc:mysql://localhost:3306/order_db?useUnicode=true
spring.shardingsphere.datasource.m1.username = root
spring.shardingsphere.datasource.m1.password = root
# 指定t_order表的主鍵生成策略為SNOWFLAKE
spring.shardingsphere.sharding.tables.t_order.key‐generator.column=order_id
spring.shardingsphere.sharding.tables.t_order.key‐generator.type=SNOWFLAKE
# 指定t_order表的數(shù)據(jù)分布情況
spring.shardingsphere.sharding.tables.t_order.actual‐data‐nodes = m1.t_order_$‐>{1..2}
# 指定t_order表的分表策略
spring.shardingsphere.sharding.tables.t_order.table‐strategy.inline.sharding‐column = order_id
spring.shardingsphere.sharding.tables.t_order.table‐strategy.inline.algorithm‐expression =
t_order_$‐>{order_id % 2 + 1}

5.4 Spring命名空間配置

此方式使用xml方式配置,不推薦使用。

<?xml version="1.0" encoding="UTF‐8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema‐instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:sharding="http://shardingsphere.apache.org/schema/shardingsphere/sharding"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring‐beans.xsd
                        http://shardingsphere.apache.org/schema/shardingsphere/sharding
                        http://shardingsphere.apache.org/schema/shardingsphere/sharding/sharding.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring‐context.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring‐tx.xsd">
    <context:annotation‐config />
   
    <!‐‐定義多個(gè)數(shù)據(jù)源‐‐>
    <bean id="m1" class="com.alibaba.druid.pool.DruidDataSource" destroy‐method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/order_db_1?useUnicode=true" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>
 
   <!‐‐定義分庫(kù)策略‐‐>
   <sharding:inline‐strategy id="tableShardingStrategy" sharding‐column="order_id" algorithm‐
expression="t_order_$‐>{order_id % 2 + 1}" />
 
   
   <!‐‐定義主鍵生成策略‐‐>
   <sharding:key‐generator id="orderKeyGenerator" type="SNOWFLAKE" column="order_id" />  
 
    <!‐‐定義sharding‐Jdbc數(shù)據(jù)源‐‐>
    <sharding:data‐source id="shardingDataSource">
        <sharding:sharding‐rule data‐source‐names="m1">
            <sharding:table‐rules>
                <sharding:table‐rule logic‐table="t_order"  table‐strategy‐
ref="tableShardingStrategy" key‐generator‐ref="orderKeyGenerator" />
            </sharding:table‐rules>
        </sharding:sharding‐rule>
    </sharding:data‐source>
</beans>

6 sharding-jdbc4種分片策略

如果我一部分表做了分庫(kù)分表,另一部分未做分庫(kù)分表的表怎么處理?怎么才能正常訪問(wèn)?

這是一個(gè)比較典型的問(wèn)題,我們知道分庫(kù)分表是針對(duì)某些數(shù)據(jù)量持續(xù)大幅增長(zhǎng)的表,比如用戶表、訂單表等,而不是一刀切將全部表都做分片。那么不分片的表和分片的表如何劃分,一般有兩種解決方案。

  • 嚴(yán)格劃分功能庫(kù),分片的庫(kù)與不分片的庫(kù)剝離開(kāi),業(yè)務(wù)代碼中按需切換數(shù)據(jù)源訪問(wèn)
  • 設(shè)置默認(rèn)數(shù)據(jù)源,以 Sharding-JDBC 為例,不給未分片表設(shè)置分片規(guī)則,它們就不會(huì)執(zhí)行,因?yàn)檎也坏铰酚梢?guī)則,這時(shí)我們?cè)O(shè)置一個(gè)默認(rèn)數(shù)據(jù)源,在找不到規(guī)則時(shí)一律訪問(wèn)默認(rèn)庫(kù)。
# 配置數(shù)據(jù)源 ds-0
spring.shardingsphere.datasource.ds-0.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.ds-0.driverClassName=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds-0.url=jdbc:mysql://47.94.6.5:3306/ds-0?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
spring.shardingsphere.datasource.ds-0.username=root
spring.shardingsphere.datasource.ds-0.password=root

# 默認(rèn)數(shù)據(jù)源,未分片的表默認(rèn)執(zhí)行庫(kù)
spring.shardingsphere.sharding.default-data-source-name=ds-0

這篇我們針對(duì)具體的SQL使用場(chǎng)景,實(shí)踐一下4種分片策略的用法,開(kāi)始前先做點(diǎn)準(zhǔn)備工作。

  • 標(biāo)準(zhǔn)分片策略
  • 復(fù)合分片策略
  • 行表達(dá)式分片策略
  • Hint分片策略

6.1 準(zhǔn)備工作

先創(chuàng)建兩個(gè)數(shù)據(jù)庫(kù) ds-0ds-1,兩個(gè)庫(kù)中分別建表 t_order_0t_order_1、t_order_2 、t_order_item_0t_order_item_1、t_order_item_2 6張表,下邊實(shí)操看看如何在不同場(chǎng)景下應(yīng)用 sharding-jdbc 的 4種分片策略。

t_order_n 表結(jié)構(gòu)如下:

CREATE TABLE `t_order_0` (
  `order_id` bigint(200) NOT NULL,
  `order_no` varchar(100) DEFAULT NULL,
  `user_id` bigint(200) NOT NULL,
  `create_name` varchar(50) DEFAULT NULL,
  `price` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

t_order_item_n 表結(jié)構(gòu)如下:

CREATE TABLE `t_order_item_0` (
  `item_id` bigint(100) NOT NULL,
  `order_id` bigint(200) NOT NULL,
  `order_no` varchar(200) NOT NULL,
  `item_name` varchar(50) DEFAULT NULL,
  `price` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

分片策略分為分表策略分庫(kù)策略,它們實(shí)現(xiàn)分片算法的方式基本相同,不同是一個(gè)對(duì)庫(kù)ds-0ds-1,一個(gè)對(duì)表 t_order_0 ··· t_order_n 等做處理。

6.2 標(biāo)準(zhǔn)分片策略

使用場(chǎng)景:SQL 語(yǔ)句中有>>=, <=,<=,INBETWEEN AND 操作符,都可以應(yīng)用此分片策略。

標(biāo)準(zhǔn)分片策略(StandardShardingStrategy),它只支持對(duì)單個(gè)分片?。ㄗ侄危橐罁?jù)的分庫(kù)分表,并提供了兩種分片算法 PreciseShardingAlgorithm(精準(zhǔn)分片)和 RangeShardingAlgorithm(范圍分片)。

在使用標(biāo)準(zhǔn)分片策略時(shí),精準(zhǔn)分片算法是必須實(shí)現(xiàn)的算法,用于 SQL 含有 =IN 的分片處理;范圍分片算法是非必選的,用于處理含有 BETWEEN AND 的分片處理。

一旦我們沒(méi)配置范圍分片算法,而 SQL 中又用到 BETWEEN AND 或者 like等,那么 SQL 將按全庫(kù)、表路由的方式逐一執(zhí)行,查詢性能會(huì)很差需要特別注意。

接下來(lái)自定義實(shí)現(xiàn) 精準(zhǔn)分片算法范圍分片算法。

6.3 精準(zhǔn)分片算法

精準(zhǔn)分庫(kù)算法

實(shí)現(xiàn)自定義精準(zhǔn)分庫(kù)、分表算法的方式大致相同,都要實(shí)現(xiàn) PreciseShardingAlgorithm 接口,并重寫 doSharding() 方法,只是配置稍有不同,而且它只是個(gè)空方法,得我們自行處理分庫(kù)、分表邏輯。其他分片策略亦如此。

SELECT * FROM t_order where  order_id = 1 or order_id in (1,2,3);

下邊我們實(shí)現(xiàn)精準(zhǔn)分庫(kù)策略,通過(guò)對(duì)分片健 order_id 取模的方式(怎么實(shí)現(xiàn)看自己喜歡)計(jì)算出 SQL 該路由到哪個(gè)庫(kù),計(jì)算出的分片庫(kù)信息會(huì)存放在分片上下文中,方便后續(xù)分表中使用。

/**
 * @author
 * @description 自定義標(biāo)準(zhǔn)分庫(kù)策略
 */
public class MyDBPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    @Override
    public String doSharding(Collection<String> databaseNames, PreciseShardingValue<Long> shardingValue) {

        /**
         * databaseNames 所有分片庫(kù)的集合
         * shardingValue 為分片屬性,其中 logicTableName 為邏輯表,columnName 分片?。ㄗ侄危?,value 為從 SQL 中解析出的分片健的值
         */
        for (String databaseName : databaseNames) {
            String value = shardingValue.getValue() % databaseNames.size() + "";
            if (databaseName.endsWith(value)) {
                return databaseName;
            }
        }
        throw new IllegalArgumentException();
    }
}

其中 Collection<String> 參數(shù)在幾種分片策略中使用一致,在分庫(kù)時(shí)值為所有分片庫(kù)的集合 databaseNames,分表時(shí)為對(duì)應(yīng)分片庫(kù)中所有分片表的集合 tablesNamesPreciseShardingValue 為分片屬性,其中 logicTableName 為邏輯表,columnName 分片健(字段),value 為從 SQL 中解析出的分片健的值。

application.properties 配置文件中只需修改分庫(kù)策略名 database-strategy 為標(biāo)準(zhǔn)模式 standard,分片算法 standard.precise-algorithm-class-name 為自定義的精準(zhǔn)分庫(kù)算法類路徑。

### 分庫(kù)策略
# 分庫(kù)分片健
spring.shardingsphere.sharding.tables.t_order.database-strategy.standard.sharding-column=order_id
# 分庫(kù)分片算法
spring.shardingsphere.sharding.tables.t_order.database-strategy.standard.precise-algorithm-class-name=com.oldlu.sharding.algorithm.dbAlgorithm.MyDBPreciseShardingAlgorithm

精準(zhǔn)分表算法

精準(zhǔn)分表算法同樣實(shí)現(xiàn) PreciseShardingAlgorithm 接口,并重寫 doSharding() 方法。

/**
 * @description 自定義標(biāo)準(zhǔn)分表策略
 */
public class MyTablePreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    @Override
    public String doSharding(Collection<String> tableNames, PreciseShardingValue<Long> shardingValue) {

        /**
         * tableNames 對(duì)應(yīng)分片庫(kù)中所有分片表的集合
         * shardingValue 為分片屬性,其中 logicTableName 為邏輯表,columnName 分片?。ㄗ侄危瑅alue 為從 SQL 中解析出的分片健的值
         */
        for (String tableName : tableNames) {
            /**
             * 取模算法,分片健 % 表數(shù)量
             */
            String value = shardingValue.getValue() % tableNames.size() + "";
            if (tableName.endsWith(value)) {
                return tableName;
            }
        }
        throw new IllegalArgumentException();
    }
}

分表時(shí) Collection<String> 參數(shù)為上邊計(jì)算出的分片庫(kù),對(duì)應(yīng)的所有分片表的集合 tablesNames;PreciseShardingValue 為分片屬性,其中 logicTableName 為邏輯表,columnName 分片?。ㄗ侄危?code>value 為從 SQL 中解析出的分片健的值。

application.properties 配置文件也只需修改分表策略名 database-strategy 為標(biāo)準(zhǔn)模式 standard,分片算法 standard.precise-algorithm-class-name 為自定義的精準(zhǔn)分表算法類路徑。

# 分表策略
# 分表分片健
spring.shardingsphere.sharding.tables.t_order.table-strategy.standard.sharding-column=order_id
# 分表算法
spring.shardingsphere.sharding.tables.t_order.table-strategy.standard.precise-algorithm-class-name=com.oldlu.sharding.algorithm.tableAlgorithm.MyTablePreciseShardingAlgorithm

看到這不難發(fā)現(xiàn),自定義分庫(kù)和分表算法的實(shí)現(xiàn)基本是一樣的,所以后邊我們只演示分庫(kù)即可

6.4 范圍分片算法

使用場(chǎng)景:當(dāng)我們 SQL中的分片健字段用到 BETWEEN AND操作符會(huì)使用到此算法,會(huì)根據(jù) SQL中給出的分片健值范圍值處理分庫(kù)、分表邏輯。

SELECT * FROM t_order where  order_id BETWEEN 1 AND 100;

自定義范圍分片算法需實(shí)現(xiàn) RangeShardingAlgorithm 接口,重寫 doSharding() 方法,下邊我通過(guò)遍歷分片健值區(qū)間,計(jì)算每一個(gè)分庫(kù)、分表邏輯。

/**
 * @description 范圍分庫(kù)算法
 */
public class MyDBRangeShardingAlgorithm implements RangeShardingAlgorithm<Integer> {

    @Override
    public Collection<String> doSharding(Collection<String> databaseNames, RangeShardingValue<Integer> rangeShardingValue) {

        Set<String> result = new LinkedHashSet<>();
        // between and 的起始值
        int lower = rangeShardingValue.getValueRange().lowerEndpoint();
        int upper = rangeShardingValue.getValueRange().upperEndpoint();
        // 循環(huán)范圍計(jì)算分庫(kù)邏輯
        for (int i = lower; i <= upper; i++) {
            for (String databaseName : databaseNames) {
                if (databaseName.endsWith(i % databaseNames.size() + "")) {
                    result.add(databaseName);
                }
            }
        }
        return result;
    }
}

和上邊的一樣 Collection<String> 在分庫(kù)、分表時(shí)分別代表分片庫(kù)名和表名集合,RangeShardingValue 這里取值方式稍有不同, lowerEndpoint 表示起始值, upperEndpoint 表示截止值。

在配置上由于范圍分片算法和精準(zhǔn)分片算法,同在標(biāo)準(zhǔn)分片策略下使用,所以只需添加上 range-algorithm-class-name 自定義范圍分片算法類路徑即可。

# 精準(zhǔn)分片算法
spring.shardingsphere.sharding.tables.t_order.database-strategy.standard.precise-algorithm-class-name=com.oldlu.sharding.algorithm.dbAlgorithm.MyDBPreciseShardingAlgorithm
# 范圍分片算法
spring.shardingsphere.sharding.tables.t_order.database-strategy.standard.range-algorithm-class-name=com.oldlu.sharding.algorithm.dbAlgorithm.MyDBRangeShardingAlgorithm

6.5 復(fù)合分片策略

使用場(chǎng)景:SQL 語(yǔ)句中有>,>=, <=<,=,INBETWEEN AND 等操作符,不同的是復(fù)合分片策略支持對(duì)多個(gè)分片健操作。

下面我們實(shí)現(xiàn)同時(shí)以 order_id、user_id 兩個(gè)字段作為分片健,自定義復(fù)合分片策略。

SELECT * FROM t_order where  user_id =0  and order_id = 1;

我們先修改一下原配置,complex.sharding-column 切換成 complex.sharding-columns 復(fù)數(shù),分片健上再加一個(gè) user_id ,分片策略名變更為 complexcomplex.algorithm-class-name 替換成我們自定義的復(fù)合分片算法。

### 分庫(kù)策略
# order_id,user_id 同時(shí)作為分庫(kù)分片健
spring.shardingsphere.sharding.tables.t_order.database-strategy.complex.sharding-column=order_id,user_id
# 復(fù)合分片算法
spring.shardingsphere.sharding.tables.t_order.database-strategy.complex.algorithm-class-name=com.oldlu.sharding.algorithm.dbAlgorithm.MyDBComplexKeysShardingAlgorithm

自定義復(fù)合分片策略要實(shí)現(xiàn) ComplexKeysShardingAlgorithm 接口,重新 doSharding()方法。

/**
 * @description 自定義復(fù)合分庫(kù)策略
 */
public class MyDBComplexKeysShardingAlgorithm implements ComplexKeysShardingAlgorithm<Integer> {


    @Override
    public Collection<String> doSharding(Collection<String> databaseNames, ComplexKeysShardingValue<Integer> complexKeysShardingValue) {

        // 得到每個(gè)分片健對(duì)應(yīng)的值
        Collection<Integer> orderIdValues = this.getShardingValue(complexKeysShardingValue, "order_id");
        Collection<Integer> userIdValues = this.getShardingValue(complexKeysShardingValue, "user_id");

        List<String> shardingSuffix = new ArrayList<>();
        // 對(duì)兩個(gè)分片健同時(shí)取模的方式分庫(kù)
        for (Integer userId : userIdValues) {
            for (Integer orderId : orderIdValues) {
                String suffix = userId % 2 + "_" + orderId % 2;
                for (String databaseName : databaseNames) {
                    if (databaseName.endsWith(suffix)) {
                        shardingSuffix.add(databaseName);
                    }
                }
            }
        }
        return shardingSuffix;
    }

    private Collection<Integer> getShardingValue(ComplexKeysShardingValue<Integer> shardingValues, final String key) {
        Collection<Integer> valueSet = new ArrayList<>();
        Map<String, Collection<Integer>> columnNameAndShardingValuesMap = shardingValues.getColumnNameAndShardingValuesMap();
        if (columnNameAndShardingValuesMap.containsKey(key)) {
            valueSet.addAll(columnNameAndShardingValuesMap.get(key));
        }
        return valueSet;
    }
}

Collection<String> 用法還是老樣子,由于支持多分片健 ComplexKeysShardingValue 分片屬性內(nèi)用一個(gè)分片健為 key,分片健值為 valuemap來(lái)存儲(chǔ)分片鍵屬性。

6.6 行表達(dá)式分片策略

行表達(dá)式分片策略(InlineShardingStrategy),在配置中使用 Groovy 表達(dá)式,提供對(duì) SQL語(yǔ)句中的 =IN 的分片操作支持,它只支持單分片健。

行表達(dá)式分片策略適用于做簡(jiǎn)單的分片算法,無(wú)需自定義分片算法,省去了繁瑣的代碼開(kāi)發(fā),是幾種分片策略中最為簡(jiǎn)單的。

它的配置相當(dāng)簡(jiǎn)潔,這種分片策略利用inline.algorithm-expression書寫表達(dá)式。

比如:ds-$->{order_id % 2} 表示對(duì) order_id 做取模計(jì)算,$ 是個(gè)通配符用來(lái)承接取模結(jié)果,最終計(jì)算出分庫(kù)ds-0 ··· ds-n,整體來(lái)說(shuō)比較簡(jiǎn)單。

# 行表達(dá)式分片鍵
sharding.jdbc.config.sharding.tables.t_order.database-strategy.inline.sharding-column=order_id
# 表達(dá)式算法
sharding.jdbc.config.sharding.tables.t_order.database-strategy.inline.algorithm-expression=ds-$->{order_id % 2}

6.7 Hint分片策略

Hint分片策略(HintShardingStrategy)相比于上面幾種分片策略稍有不同,這種分片策略無(wú)需配置分片健,分片健值也不再?gòu)?SQL中解析,而是由外部指定分片信息,讓 SQL在指定的分庫(kù)、分表中執(zhí)行。ShardingSphere 通過(guò) Hint API實(shí)現(xiàn)指定操作,實(shí)際上就是把分片規(guī)則tableruledatabaserule由集中配置變成了個(gè)性化配置。

舉個(gè)例子,如果我們希望訂單表t_orderuser_id 做分片健進(jìn)行分庫(kù)分表,但是 t_order 表中卻沒(méi)有 user_id 這個(gè)字段,這時(shí)可以通過(guò) Hint API 在外部手動(dòng)指定分片健或分片庫(kù)。

下邊我們這邊給一條無(wú)分片條件的SQL,看如何指定分片健讓它路由到指定庫(kù)表。

SELECT * FROM t_order;

使用 Hint分片策略同樣需要自定義,實(shí)現(xiàn) HintShardingAlgorithm 接口并重寫 doSharding()方法。

/**
 * @description hit分表算法
 */
public class MyTableHintShardingAlgorithm implements HintShardingAlgorithm<String> {

    @Override
    public Collection<String> doSharding(Collection<String> tableNames, HintShardingValue<String> hintShardingValue) {

        Collection<String> result = new ArrayList<>();
        for (String tableName : tableNames) {
            for (String shardingValue : hintShardingValue.getValues()) {
                if (tableName.endsWith(String.valueOf(Long.valueOf(shardingValue) % tableNames.size()))) {
                    result.add(tableName);
                }
            }
        }
        return result;
    }
}

自定義完算法只實(shí)現(xiàn)了一部分,還需要在調(diào)用 SQL 前通過(guò) HintManager 指定分庫(kù)、分表信息。由于每次添加的規(guī)則都放在 ThreadLocal 內(nèi),所以要先執(zhí)行 clear() 清除掉上一次的規(guī)則,否則會(huì)報(bào)錯(cuò);addDatabaseShardingValue 設(shè)置分庫(kù)分片健鍵值,addTableShardingValue設(shè)置分表分片健鍵值。setMasterRouteOnly 讀寫分離強(qiáng)制讀主庫(kù),避免造成主從復(fù)制導(dǎo)致的延遲。

// 清除掉上一次的規(guī)則,否則會(huì)報(bào)錯(cuò)
HintManager.clear();
// HintManager API 工具類實(shí)例
HintManager hintManager = HintManager.getInstance();
// 直接指定對(duì)應(yīng)具體的數(shù)據(jù)庫(kù)
hintManager.addDatabaseShardingValue("ds",0);
// 設(shè)置表的分片健
hintManager.addTableShardingValue("t_order" , 0);
hintManager.addTableShardingValue("t_order" , 1);
hintManager.addTableShardingValue("t_order" , 2);

// 在讀寫分離數(shù)據(jù)庫(kù)中,Hint 可以強(qiáng)制讀主庫(kù)
hintManager.setMasterRouteOnly();

debug 調(diào)試看到,我們對(duì) t_order 表設(shè)置分表分片健鍵值,可以在自定義的算法 HintShardingValue 參數(shù)中成功拿到。

properties 文件中配置無(wú)需再指定分片健,只需自定義的 Hint分片算法類路徑即可。

# Hint分片算法
spring.shardingsphere.sharding.tables.t_order.table-strategy.hint.algorithm-class-name=com.oldlu.sharding.algorithm.tableAlgorithm.MyTableHintShardingAlgorithm

7 水平分表

上述案例為水平分表是在同一個(gè)數(shù)據(jù)庫(kù)內(nèi),把同一個(gè)表的數(shù)據(jù)按一定規(guī)則拆到多個(gè)表中,我們已經(jīng)對(duì)水平分庫(kù)進(jìn)行實(shí)現(xiàn),這里不再重復(fù)介紹。

8 水平分庫(kù)

前面已經(jīng)介紹過(guò),水平分庫(kù)是把同一個(gè)表的數(shù)據(jù)按一定規(guī)則拆到不同的數(shù)據(jù)庫(kù)中,每個(gè)庫(kù)可以放在不同的服務(wù)器上。接下來(lái)看一下如何使用Sharding-JDBC實(shí)現(xiàn)水平分庫(kù),咱們繼續(xù)對(duì)快速入門中的例子進(jìn)行完善。

(1)將原有order_db庫(kù)拆分為order_db_1、order_db_2

(2)分片規(guī)則修改

由于數(shù)據(jù)庫(kù)拆分了兩個(gè),這里需要配置兩個(gè)數(shù)據(jù)源。

分庫(kù)需要配置分庫(kù)的策略,和分表策略的意義類似,通過(guò)分庫(kù)策略實(shí)現(xiàn)數(shù)據(jù)操作針對(duì)分庫(kù)的數(shù)據(jù)庫(kù)進(jìn)行操作。

# 定義多個(gè)數(shù)據(jù)源
spring.shardingsphere.datasource.names = m1,m2
spring.shardingsphere.datasource.m1.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m1.driver‐class‐name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.m1.url = jdbc:mysql://localhost:3306/order_db_1?useUnicode=true
spring.shardingsphere.datasource.m1.username = root
spring.shardingsphere.datasource.m1.password = root
spring.shardingsphere.datasource.m2.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m2.driver‐class‐name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.m2.url = jdbc:mysql://localhost:3306/order_db_2?useUnicode=true
spring.shardingsphere.datasource.m2.username = root
spring.shardingsphere.datasource.m2.password = root
...
# 分庫(kù)策略,以u(píng)ser_id為分片鍵,分片策略為user_id % 2 + 1,user_id為偶數(shù)操作m1數(shù)據(jù)源,否則操作m2。
spring.shardingsphere.sharding.tables.t_order.database‐strategy.inline.sharding‐column = user_id
spring.shardingsphere.sharding.tables.t_order.database‐strategy.inline.algorithm‐expression =
m$‐>{user_id % 2 + 1}

分庫(kù)策略定義方式如下:

#分庫(kù)策略,如何將一個(gè)邏輯表映射到多個(gè)數(shù)據(jù)源
spring.shardingsphere.sharding.tables.<邏輯表名稱>.database‐strategy.<分片策略>.<分片策略屬性名>= #
分片策略屬性值
#分表策略,如何將一個(gè)邏輯表映射為多個(gè)實(shí)際表
spring.shardingsphere.sharding.tables.<邏輯表名稱>.table‐strategy.<分片策略>.<分片策略屬性名>= #分
片策略屬性值

Sharding-JDBC支持以下幾種分片策略:

不管理分庫(kù)還是分表,策略基本一樣。 

  • standard :標(biāo)準(zhǔn)分片策略,對(duì)應(yīng)StandardShardingStrategy。提供對(duì)SQL語(yǔ)句中的=, IN和BETWEEN AND的分片操作支持。StandardShardingStrategy只支持單分片鍵,提供PreciseShardingAlgorithm和
  • RangeShardingAlgorithm兩個(gè)分片算法。PreciseShardingAlgorithm是必選的,用于處理=和IN的分片。RangeShardingAlgorithm是可選的,用于處理BETWEEN AND分片,如果不配置 RangeShardingAlgorithm,SQL中的BETWEEN AND將按照全庫(kù)路由處理。
  • complex :符合分片策略,對(duì)應(yīng)ComplexShardingStrategy。復(fù)合分片策略。提供對(duì)SQL語(yǔ)句中的=, IN
  • 和BETWEEN AND的分片操作支持。ComplexShardingStrategy支持多分片鍵,由于多分片鍵之間的關(guān)系復(fù)雜,因此并未進(jìn)行過(guò)多的封裝,而是直接將分片鍵值組合以及分片操作符透?jìng)髦练制惴?,完全由?yīng)用開(kāi)發(fā)者實(shí)現(xiàn),提供最大的靈活度。
  • inline :行表達(dá)式分片策略,對(duì)應(yīng)InlineShardingStrategy。使用Groovy的表達(dá)式,提供對(duì)SQL語(yǔ)句中的=和
  • IN的分片操作支持,只支持單分片鍵。對(duì)于簡(jiǎn)單的分片算法,可以通過(guò)簡(jiǎn)單的配置使用,從而避免繁瑣的Java代碼開(kāi)發(fā),如: t_user_$ ->{u_id % 8} 表示t_user表根據(jù)u_id模8,而分成8張表,表名稱為 t_user_0 到t_user_7 。
  • hint :Hint分片策略,對(duì)應(yīng)HintShardingStrategy。通過(guò)Hint而非SQL解析的方式分片的策略。對(duì)于分片字段非SQL決定,而由其他外置條件決定的場(chǎng)景,可使用SQL Hint靈活的注入分片字段。例:內(nèi)部系統(tǒng),按照員工登錄主鍵分庫(kù),而數(shù)據(jù)庫(kù)中并無(wú)此字段。SQL Hint支持通過(guò)Java API和SQL注釋(待實(shí)現(xiàn))兩種方式使用。none :不分片策略,對(duì)應(yīng)NoneShardingStrategy。不分片的策略。

(3) 插入測(cè)試

修改testInsertOrder方法,插入數(shù)據(jù)中包含不同的user_id

@Test
public void testInsertOrder(){
    for (int i = 0 ; i<10; i++){
        orderDao.insertOrder(new BigDecimal((i+1)*5),1L,"WAIT_PAY");
    }
    for (int i = 0 ; i<10; i++){
        orderDao.insertOrder(new BigDecimal((i+1)*10),2L,"WAIT_PAY");
    }
}

執(zhí)行testInsertOrder:

通過(guò)日志可以看出,根據(jù)user_id的奇偶不同,數(shù)據(jù)分別落在了不同數(shù)據(jù)源,達(dá)到目標(biāo)。

(4)查詢測(cè)試

調(diào)用快速入門的查詢接口進(jìn)行測(cè)試:

List<Map> selectOrderbyIds(@Param("orderIds")List<Long> orderIds); 

通過(guò)日志發(fā)現(xiàn),sharding-jdbc將sql路由到m1和m2:

問(wèn)題分析:

由于查詢語(yǔ)句中并沒(méi)有使用分片鍵user_id,所以sharding-jdbc將廣播路由到每個(gè)數(shù)據(jù)結(jié)點(diǎn)。

下邊我們?cè)趕ql中添加分片鍵進(jìn)行查詢。

在OrderDao中定義接口:

@Select({"<script>", 
        " select",
        " * ",
        " from t_order t ",
        "where t.order_id in",
        "<foreach collection='orderIds' item='id' open='(' separator=',' close=')'>",
        "#{id}",
        "</foreach>",
        " and t.user_id = #{userId} ",
        "</script>"
})
List<Map> selectOrderbyUserAndIds(@Param("userId") Integer userId,@Param("orderIds")List<Long>
orderIds);

編寫測(cè)試方法:

@Test 
public void testSelectOrderbyUserAndIds(){
    List<Long> orderIds = new ArrayList<>();
    orderIds.add(373422416644276224L);
    orderIds.add(373422415830581248L);
    //查詢條件中包括分庫(kù)的鍵user_id
    int user_id = 1;
    List<Map> orders = orderDao.selectOrderbyUserAndIds(user_id,orderIds);
    JSONArray jsonOrders = new JSONArray(orders);
    System.out.println(jsonOrders);
}

執(zhí)行testSelectOrderbyUserAndIds:

查詢條件user_id為1,根據(jù)分片策略m$->{user_id % 2 + 1}計(jì)算得出m2,此sharding-jdbc將sql路由到m2,見(jiàn)上圖日志。

9 垂直分庫(kù)

前面已經(jīng)介紹過(guò),垂直分庫(kù)是指按照業(yè)務(wù)將表進(jìn)行分類,分布到不同的數(shù)據(jù)庫(kù)上面,每個(gè)庫(kù)可以放在不同的服務(wù)器上,它的核心理念是專庫(kù)專用。接下來(lái)看一下如何使用Sharding-JDBC實(shí)現(xiàn)垂直分庫(kù)。

(1)創(chuàng)建數(shù)據(jù)庫(kù)

創(chuàng)建數(shù)據(jù)庫(kù)user_db 

CREATE DATABASE user_db CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';

在user_db中創(chuàng)建t_user表

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (
  `user_id` bigint(20) NOT NULL COMMENT '用戶id',
  `fullname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用戶姓名',
  `user_type` char(1) DEFAULT NULL COMMENT '用戶類型',
  PRIMARY KEY (`user_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

(2)在Sharding-JDBC規(guī)則中修改

# 新增m0數(shù)據(jù)源,對(duì)應(yīng)user_db
spring.shardingsphere.datasource.names = m0,m1,m2
...
spring.shardingsphere.datasource.m0.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m0.driver‐class‐name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.m0.url = jdbc:mysql://localhost:3306/user_db?useUnicode=true
spring.shardingsphere.datasource.m0.username = root
spring.shardingsphere.datasource.m0.password = root
....
# t_user分表策略,固定分配至m0的t_user真實(shí)表
spring.shardingsphere.sharding.tables.t_user.actual‐data‐nodes = m$‐>{0}.t_user
spring.shardingsphere.sharding.tables.t_user.table‐strategy.inline.sharding‐column = user_id
spring.shardingsphere.sharding.tables.t_user.table‐strategy.inline.algorithm‐expression = t_user

(3) 數(shù)據(jù)操作

新增UserDao:

@Mapper
@Component
public interface UserDao {
    /**
     * 新增用戶
     * @param userId 用戶id
     * @param fullname 用戶姓名
     * @return
     */
    @Insert("insert into t_user(user_id, fullname) value(#{userId},#{fullname})")
    int insertUser(@Param("userId")Long userId,@Param("fullname")String fullname);
    /**
     * 根據(jù)id列表查詢多個(gè)用戶
     * @param userIds 用戶id列表
     * @return
     */
    @Select({"<script>",
            " select",
            " * ",
            " from t_user t ",
            " where t.user_id in",
            "<foreach collection='userIds' item='id' open='(' separator=',' close=')'>",
            "#{id}",
            "</foreach>",
            "</script>"
    })
    List<Map> selectUserbyIds(@Param("userIds")List<Long> userIds);
}

(4)測(cè)試

新增單元測(cè)試方法:

@Test
public void testInsertUser(){
    for (int i = 0 ; i<10; i++){
        Long id = i + 1L;
        userDao.insertUser(id,"姓名"+ id );
    }
}
@Test
public void testSelectUserbyIds(){
    List<Long> userIds = new ArrayList<>();
    userIds.add(1L);
    userIds.add(2L);
    List<Map> users = userDao.selectUserbyIds(userIds);
    System.out.println(users);
}

執(zhí)行 testInsertUser:

通過(guò)日志可以看出t_user表的數(shù)據(jù)被落在了m0數(shù)據(jù)源,達(dá)到目標(biāo)。

執(zhí)行testSelectUserbyIds:

通過(guò)日志可以看出t_user表的查詢操作被落在了m0數(shù)據(jù)源,達(dá)到目標(biāo)。

10 公共表

公共表屬于系統(tǒng)中數(shù)據(jù)量較小,變動(dòng)少,而且屬于高頻聯(lián)合查詢的依賴表。參數(shù)表、數(shù)據(jù)字典表等屬于此類型??梢詫⑦@類表在每個(gè)數(shù)據(jù)庫(kù)都保存一份,所有更新操作都同時(shí)發(fā)送到所有分庫(kù)執(zhí)行。接下來(lái)看一下如何使用Sharding-JDBC實(shí)現(xiàn)公共表。

(1)創(chuàng)建數(shù)據(jù)庫(kù)

分別在user_db、order_db_1、order_db_2中創(chuàng)建t_dict表:

CREATE TABLE `t_dict`  (
  `dict_id` bigint(20) NOT NULL COMMENT '字典id',
  `type` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '字典類型',
  `code` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '字典編碼',
  `value` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '字典值',
  PRIMARY KEY (`dict_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

(2)在Sharding-JDBC規(guī)則中修改

# 指定t_dict為公共表
spring.shardingsphere.sharding.broadcast‐tables=t_dict

(3)數(shù)據(jù)操作

新增DictDao:

@Mapper
@Component
public interface DictDao {
    /**
     * 新增字典
     * @param type 字典類型
     * @param code 字典編碼
     * @param value 字典值
     * @return
     */
    @Insert("insert into t_dict(dict_id,type,code,value) value(#{dictId},#{type},#[code],#
{value})")
    int insertDict(@Param("dictId") Long dictId,@Param("type") String type, @Param("code")String
code, @Param("value")String value);
    /**
     * 刪除字典
     * @param dictId 字典id
     * @return
     */
    @Delete("delete from t_dict where dict_id = #{dictId}")
    int deleteDict(@Param("dictId") Long dictId);
}

(4)字典操作測(cè)試

新增單元測(cè)試方法:

@Test
public void testInsertDict(){
dictDao.insertDict(1L,"user_type","0","管理員");    
dictDao.insertDict(2L,"user_type","1","操作員");    
}
@Test
public void testDeleteDict(){
dictDao.deleteDict(1L);    
dictDao.deleteDict(2L);    
}

執(zhí)行testInsertDict:

通過(guò)日志可以看出,對(duì)t_dict的表的操作被廣播至所有數(shù)據(jù)源。

測(cè)試刪除字典,觀察是否把所有數(shù)據(jù)源中該 公共表的記錄刪除。

(5)字典關(guān)聯(lián)查詢測(cè)試

字典表已在各各分庫(kù)存在,各業(yè)務(wù)表即可和字典表關(guān)聯(lián)查詢。

定義用戶關(guān)聯(lián)查詢dao:

在UserDao中定義:

/**
 * 根據(jù)id列表查詢多個(gè)用戶,關(guān)聯(lián)查詢字典表
 * @param userIds 用戶id列表
 * @return
 */
@Select({"<script>",
        " select",
        " * ",
        " from t_user t ,t_dict b",
        " where t.user_type = b.code and t.user_id in",
        "<foreach collection='userIds' item='id' open='(' separator=',' close=')'>",
        "#{id}",
        "</foreach>",
        "</script>"
})
List<Map> selectUserInfobyIds(@Param("userIds")List<Long> userIds);

定義測(cè)試方法:

@Test 
public void testSelectUserInfobyIds(){
    List<Long> userIds = new ArrayList<>();
    userIds.add(1L);
    userIds.add(2L);
    List<Map> users = userDao.selectUserInfobyIds(userIds);
    JSONArray jsonUsers = new JSONArray(users);
    System.out.println(jsonUsers);
}

執(zhí)行測(cè)試方法,查看日志,成功關(guān)聯(lián)查詢字典表:

11 配置中遇到的一些問(wèn)題

11.1 數(shù)據(jù)庫(kù)鏈接池找不到

springboot2.0之后,采用的默認(rèn)數(shù)據(jù)庫(kù)連接池就是Hikari

11.2 錯(cuò)誤java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.

原因

  • HikariConfig校驗(yàn)配置中沒(méi)有jdbcUrl配置

處理方式

  • springboot 1.x 版本中,數(shù)據(jù)源配置是 xxxx.url=
  • 在2.x中,更改為 jdbc-url

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • MySQL數(shù)據(jù)庫(kù)備份恢復(fù)實(shí)現(xiàn)代碼

    MySQL數(shù)據(jù)庫(kù)備份恢復(fù)實(shí)現(xiàn)代碼

    這篇文章主要介紹了MySQL數(shù)據(jù)庫(kù)備份恢復(fù)實(shí)現(xiàn)代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-06-06
  • 查看連接mysql的IP地址的實(shí)例方法

    查看連接mysql的IP地址的實(shí)例方法

    在本篇文章里小編給大家分享的是一篇關(guān)于查看連接mysql的IP地址的實(shí)例方法,有需要的朋友們可以參考下。
    2020-10-10
  • MySQL UPDATE 語(yǔ)句的非標(biāo)準(zhǔn)實(shí)現(xiàn)代碼

    MySQL UPDATE 語(yǔ)句的非標(biāo)準(zhǔn)實(shí)現(xiàn)代碼

    這篇文章主要介紹了MySQL UPDATE 語(yǔ)句的非標(biāo)準(zhǔn)實(shí)現(xiàn)代碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-04-04
  • mysql 5.7.21解壓版安裝配置方法圖文教程(win10)

    mysql 5.7.21解壓版安裝配置方法圖文教程(win10)

    這篇文章主要為大家詳細(xì)介紹了win10下mysql 5.7.21解壓版安裝配置方法圖文教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-02-02
  • KubeSphere部署mysql的詳細(xì)步驟

    KubeSphere部署mysql的詳細(xì)步驟

    本文介紹了在KubeSphere中部署Mysql的詳細(xì)步驟,包括創(chuàng)建mysql配置、pvc掛載、工作負(fù)載、服務(wù),并測(cè)試數(shù)據(jù)庫(kù)連接,步驟詳盡,包括yaml配置和環(huán)境變量設(shè)置,特別強(qiáng)調(diào)了路徑一致性和外部訪問(wèn)設(shè)置,還提到了使用NodePort模式解決自定義域名連接問(wèn)題
    2024-10-10
  • mysql 8.0.12 安裝配置方法圖文教程(windows10)

    mysql 8.0.12 安裝配置方法圖文教程(windows10)

    這篇文章主要為大家詳細(xì)介紹了windows10下mysql 8.0.12 安裝配置方法圖文教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-08-08
  • mysql如何將sql查詢的結(jié)果以百分比展示出來(lái)

    mysql如何將sql查詢的結(jié)果以百分比展示出來(lái)

    這篇文章主要給大家介紹了關(guān)于mysql如何將sql查詢的結(jié)果以百分比展示出來(lái)的相關(guān)資料,用到了MySQL字符串處理中的兩個(gè)函數(shù)concat()和left()實(shí)現(xiàn)查詢結(jié)果以百分比顯示,需要的朋友可以參考下
    2023-08-08
  • mysql中找不到my.ini文件的問(wèn)題及解決

    mysql中找不到my.ini文件的問(wèn)題及解決

    這篇文章主要介紹了mysql中找不到my.ini文件的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • MySQL中的JSON_CONTAINS函數(shù)舉例詳解

    MySQL中的JSON_CONTAINS函數(shù)舉例詳解

    這篇文章主要給大家介紹了關(guān)于MySQL中JSON_CONTAINS函數(shù)舉例詳解的相關(guān)資料,MySQL JSON_CONTAINS函數(shù)可用于判斷JSON數(shù)組中是否包含某個(gè)元素,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-12-12
  • MySQL為例講解JDBC數(shù)據(jù)庫(kù)連接步驟

    MySQL為例講解JDBC數(shù)據(jù)庫(kù)連接步驟

    這篇文章主要為大家詳細(xì)介紹了MySQL為例講解JDBC數(shù)據(jù)庫(kù)連接步驟,感興趣的小伙伴們可以參考一下
    2016-08-08

最新評(píng)論