主键生成策略

主键生成策略

自动自增

  1. 数据库中设置
CREATE TABLE `user`
(
    `id`       int NOT NULL AUTO_INCREMENT,
    -- id 自增
    `username` varchar(12) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
    `sex`      varchar(2) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
    `age`      int NULL DEFAULT NULL,
    `birthday` date NULL DEFAULT NULL,
    PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 554 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

UUID

  1. 通用唯一识别码
package com.xiang;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.UUID;

/**
 * Created by IntelliJ IDEA.
 * User: xiang
 * Date: 2021/10/21 15:04
 */
@SpringBootTest
public class UUIDTest {

    @Test
    void UUIDT1() {
        String s = UUID.randomUUID().toString();
        String s2 = UUID.randomUUID().toString();
        String s3 = UUID.randomUUID().toString();
        String s4 = UUID.randomUUID().toString();

        System.out.println(s);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println(s4);
    }

}

运行结果
2021-10-21 15:06:24.178  INFO 11772 --- [           main] com.xiang.UUIDTest                       : Started UUIDTest in 3.605 seconds (JVM running for 5.141)
c8743ea0-a14c-46d4-92b8-859db7d6fc37
078744d3-ea73-4b4a-8929-1bbd68d15ccf
2e2f2b52-5dd2-430d-99b0-de90de1deb93
ce251f59-b846-4d9a-ac0b-b531813563af

Resid

假如一个集群中有5台Redis。可以初始化每台Redis的值分别是1,2,3,4,5,然后步长都是5。各个Redis生成的ID为:

A:1,6,11,16,21 

B:2,7,12,17,22

C:3,8,13,18,23 

D:4,9,14,19,24 

E:5,10,15,20,25
posted @ 2021-10-21 16:22  阿向向  阅读(80)  评论(0编辑  收藏  举报