当前位置:网站首页>Implementation of MySQL custom sequence number

Implementation of MySQL custom sequence number

2022-06-23 05:29:00 Daydayup, and

One 、 Preface

In many cases , We need to use our own unique Id Or a serial number guaranteed not to be repeated , Especially in high concurrency scenarios . So , It is easy to think of the following implementation methods :

  • Use through atomic manipulation and locking mechanisms Java Code implementation , In the single JVM Maintain the number of sequences in memory , In addition, you need to ensure that it is persisted to the external storage system ;
  • Or use components that ensure high distribution and consistency Zookeeper, With its distributed locks, it is easy to implement , The disadvantage is that you need to introduce Zookeeper The components of depend on , Undoubtedly, it increases the complexity and maintainability of the system ( Switch to a Redis It's the same thing );
  • Another easy idea is to use MySQL Transaction operation of , Stored procedures can meet the requirements of transaction , So this method is lighter than the first method .

Here is the introduction of using customization MySQL Sequence number to generate unique Id.

Two 、 Create sequence table

DROP TABLE
    IF EXISTS sequence;
CREATE TABLE
    sequence
    (
        name VARCHAR(50) NOT NULL,
        current_value BIGINT NOT NULL,
        increment INT NOT NULL DEFAULT 1,
        PRIMARY KEY (name)
    )
    ENGINE=InnoDB;

3、 ... and 、 Insert defined sequence

INSERT INTO sequence VALUES ('seq1', 0, 1);
INSERT INTO sequence VALUES ('seq2', 0, 1);
...

Four 、 Custom function implementation

DROP FUNCTION IF EXISTS `seq`;  
DELIMITER $$  
CREATE FUNCTION `seq`(seq_name char (20)) returns BIGINT
BEGIN
  UPDATE sequence SET current_value=last_insert_id(current_value + increment) WHERE name=seq_name;
  RETURN last_insert_id();
END $$
DELIMITER ;

5、 ... and 、MyBatis To get the latest sequence number

<select id="getRowkeyByName" parameterType="java.lang.String" resultType="long">
    select `seq`(
        #{name}
    )
</select>

above .

原网站

版权声明
本文为[Daydayup, and]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230323329540.html