溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么使用sharding-jdbc實現(xiàn)水平分表

發(fā)布時間:2021-11-03 11:06:59 來源:億速云 閱讀:207 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“怎么使用sharding-jdbc實現(xiàn)水平分表”,在日常操作中,相信很多人在怎么使用sharding-jdbc實現(xiàn)水平分表問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”怎么使用sharding-jdbc實現(xiàn)水平分表”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

mysql中新建數(shù)據(jù)庫sharding_db,新增兩張結(jié)構(gòu)一樣的表student_1和student_2。

CREATE TABLE `student_1` (
`ID`  bigint(20) NOT NULL ,
`NAME`  varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL ,
`AGE`  int(11) NOT NULL ,
`GENDER`  varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL ,
PRIMARY KEY (`ID`)
);

此處未指定主鍵自增,因為兩張表的id不能重復,所以只能從后端傳入id。

添加依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Druid連接池 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.20</version>
</dependency>

<!-- Mysql驅(qū)動依賴 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<!-- MybatisPlus -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.0.5</version>
</dependency>

<!-- Sharding-JDBC -->
<dependency>
    <groupId>org.apache.shardingsphere</groupId>
    <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
    <version>4.0.0-RC1</version>
</dependency>

<!-- lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-test</artifactId>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

編寫配置文件

spring.main.allow-bean-definition-overriding=true

# 配置Sharding-JDBC的分片策略
# 配置數(shù)據(jù)源,給數(shù)據(jù)源起名g1,g2...此處可配置多數(shù)據(jù)源
spring.shardingsphere.datasource.names=g1

# 配置數(shù)據(jù)源具體內(nèi)容:連接池,驅(qū)動,地址,用戶名,密碼
# 由于上面配置數(shù)據(jù)源只有g(shù)1因此下面只配置g1.type,g1.driver-class-name,g1.url,g1.username,g1.password
spring.shardingsphere.datasource.g1.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.g1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.g1.url=jdbc:mysql://localhost:3306/sharding_db?characterEncoding=utf-8&useUnicode=true&useSSL=false&serverTimezone=UTC
spring.shardingsphere.datasource.g1.username=root
spring.shardingsphere.datasource.g1.password=123456

# 配置表的分布,表的策略
spring.shardingsphere.sharding.tables.student.actual-data-nodes=g1.student_$->{1..2}

# 指定student表 主鍵gid 生成策略為 SNOWFLAKE
spring.shardingsphere.sharding.tables.student.key-generator.column=id
spring.shardingsphere.sharding.tables.student.key-generator.type=SNOWFLAKE

# 指定分片策略 約定id值是偶數(shù)添加到student_1表,如果id是奇數(shù)添加到student_2表
spring.shardingsphere.sharding.tables.student.table-strategy.inline.sharding-column=id
spring.shardingsphere.sharding.tables.student.table-strategy.inline.algorithm-expression=student_$->{id % 2 + 1}

# 打開sql輸出日志
spring.shardingsphere.props.sql.show=true

或者是yml格式

spring:
  main:
    allow-bean-definition-overriding: true
  shardingsphere:
    datasource:
      g1:
        driver-class-name: com.mysql.cj.jdbc.Driver
        password: 123456
        type: com.alibaba.druid.pool.DruidDataSource
        url: jdbc:mysql://localhost:3306/sharding_db?characterEncoding=utf-8&useUnicode=true&useSSL=false&serverTimezone=UTC
        username: root
      names: g1
    props:
      sql:
        show: true
    sharding:
      tables:
        student:
          actual-data-nodes: g1.student_$->{1..2}
          key-generator:
            column: id
            type: SNOWFLAKE
          table-strategy:
            inline:
              algorithm-expression: student_$->{id % 2 + 1}
              sharding-column: id

編寫實體類

@Data
public class Student {
    private Long id;
    private String name;
    private int age;
    private String gender;
}

編寫mapper接口

@Repository
public interface StudentMapper extends BaseMapper<Student> {

}

編寫測試類

@SpringBootTest
class ShardingJdbcDemoApplicationTests {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void test01() {
        for (int i = 0; i < 10; i++) {
            Student student = new Student();
            student.setName("wuwl");
            student.setAge(27);
            student.setGender("男");
            studentMapper.insert(student);
        }
    }
}

執(zhí)行測試

怎么使用sharding-jdbc實現(xiàn)水平分表

執(zhí)行成功,主鍵通過雪花算法在后端生成,傳入到數(shù)據(jù)庫中,根據(jù)奇偶性進行分表。

student_1表數(shù)據(jù):

怎么使用sharding-jdbc實現(xiàn)水平分表

student_2表數(shù)據(jù):

怎么使用sharding-jdbc實現(xiàn)水平分表

兩張表的數(shù)據(jù)分別有5條,但這只是因為雪花算法生成的id奇數(shù)偶數(shù)各5個,不是1:1的關(guān)系,需要注意。
主鍵生成后,根據(jù)策略插入到對應的表中,從打印出來的sql可以證明這一點。
通過mapper接口的selectById方法進行查詢時,會先根據(jù)主鍵策略判斷在哪個庫,再直接去那個庫根據(jù)主鍵查詢。而如果是通過其它條件查詢,或者是多個id的selectById方法查詢,又是如何的呢?

@Test
    public void test03() {
        List<Long> list = new ArrayList<>();
        list.add(1362282042768609282l);
        list.add(1362282040277192705l);
        List<Student> studentList = studentMapper.selectBatchIds(list);
        System.out.println(studentList);
    }

取了兩張表的id進行查詢。

怎么使用sharding-jdbc實現(xiàn)水平分表

執(zhí)行同樣的sql,在兩張表中都查詢一遍,再組合結(jié)果。
如果所有的id,都來自同一張表,那是否會去多個表中重復查詢呢?

怎么使用sharding-jdbc實現(xiàn)水平分表

只執(zhí)行了一遍。所以,在執(zhí)行查詢時,sharding會先判斷是否可以確定需要的數(shù)據(jù)來自那張表,如果能,則直接去那一張表中查詢數(shù)據(jù)即可,而如果不能確定,則會多個表重復查詢,以確定查詢結(jié)果的完整性。

到此,關(guān)于“怎么使用sharding-jdbc實現(xiàn)水平分表”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI