Method, system and equipment for generating regularized ID (Identity) in high-concurrency scene and medium
By leveraging Redis atomic auto-increment and distributed lock technologies, custom rule-based IDs are generated, resolving concurrency bottlenecks and duplicate sequence number issues in high-concurrency scenarios. This achieves efficient and unique ID generation, suitable for high-frequency businesses such as e-commerce and finance.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-12-17
- Publication Date
- 2026-04-07
AI Technical Summary
Existing rule-based ID generation solutions suffer from concurrency bottlenecks, duplicate serial numbers, inflexible formats, and inability to reset monthly in high-concurrency scenarios, making it difficult to meet the requirements of custom rule-based formats and high-concurrency processing capabilities.
The system uses Redis's atomic auto-increment feature to generate monthly incrementing serial numbers, combines the business prefix with the year and month to form a regular ID, and uses a Redis key expiration policy to reset the serial numbers monthly. It also uses a distributed lock to ensure uniqueness under high concurrency and utilizes a Redis cluster and distributed lock module to ensure generation efficiency and consistency.
It enables the generation of IDs with customizable rule formats, avoiding duplicate or broken serial numbers, improving the reliability and efficiency of ID generation, adapting to high-frequency business scenarios, reducing operation and maintenance costs, and supporting global consistency across multiple application instances.
Smart Images

Figure CN121807267A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of Java backend distributed system development technology, specifically a method, system, device, and medium for generating regularized IDs in high-concurrency scenarios. Background Technology
[0002] In Java backend business systems, rule-based IDs serve as unique identifiers for business data. They must not only be unique but also carry business attributes (such as business type and generation time) to facilitate data traceability and management. Rule-based IDs (such as combined IDs containing business identifiers, time information, and serial numbers) are widely used in business scenarios such as orders, transaction logs, and vouchers. They must meet the core requirements of uniform format, ordered incremental serial numbers, and no duplication under high concurrency. Existing rule-based ID generation solutions suffer from concurrency bottlenecks due to database auto-incrementing, while local cache auto-incrementing is prone to serial number duplication. Simple distributed ID generation solutions struggle to adapt to custom business rule formats. A typical rule-based ID format is "business prefix + year / month + incremental serial number" (e.g., CG202512001, where "CG" is the business prefix, "202512" is the year / month, and "001" is the monthly incremental serial number). Such IDs must meet the core requirement that "the serial number restarts from 001 each month."
[0003] Existing rule-based ID generation schemes have the following shortcomings:
[0004] (1) Database auto-increment scheme: The database table field is used as the basis for generating the serial number. The maximum serial number of the current year and month is queried by SQL and then incremented by 1. This method is feasible in low-concurrency scenarios, but in high-concurrency scenarios, a large number of database lock competition will occur, resulting in ID generation response delay, or even deadlock, which cannot meet the needs of high-frequency business.
[0005] (2) Local cache auto-increment scheme: The application caches the maximum sequence number of the current year and month locally, and increments it locally each time an ID is generated. Although this method has a fast response speed, in a distributed deployment scenario, the local cache data of multiple application instances cannot be synchronized, which is prone to duplicate sequence numbers. In addition, the loss of cache after the application restarts will cause a gap in sequence numbers (such as starting from 001 after restarting, which conflicts with the historical sequence number).
[0006] (3) General distributed ID scheme (such as snowflake algorithm): Although it can guarantee uniqueness under high concurrency, the ID format is long integer, which cannot customize business prefix, year and month and other rule information. It requires additional storage of business attribute related data, which increases the complexity of the system.
[0007] (4) Redis auto-increment without year-month cycle: Some solutions directly use Redis auto-increment keys to generate serial numbers, but do not design a serial number reset mechanism for the year and month dimension, resulting in infinitely increasing serial numbers, which cannot meet the business requirement of "starting from 001 every month". Among them, Redis, as a high-performance distributed cache, supports atomic auto-increment operation (INCR) and has the characteristics of data sharing in a distributed environment. Its single-threaded model can guarantee the atomicity of operations under high concurrency. Combined with the expiration policy, it can realize the monthly reset of serial numbers, making it an ideal technology choice to solve the problem of high concurrency of regular IDs.
[0008] Therefore, how to meet the requirements of custom rule-based formatting, while also having high concurrency processing capabilities, avoiding serial number duplication or gaps, and improving the reliability and efficiency of ID generation is a technical problem that urgently needs to be solved. Summary of the Invention
[0009] The technical objective of this invention is to provide a method, system, device, and medium for generating regularized IDs in high-concurrency scenarios, in order to solve the problem of how to meet the requirements of custom regularized formats, have high concurrency processing capabilities, avoid serial number duplication or gaps, and improve the reliability and efficiency of ID generation.
[0010] The technical objective of this invention is achieved as follows: a method for generating regularized IDs in high-concurrency scenarios. This method generates monthly incrementing serial numbers based on Redis's atomic auto-increment feature, combines a business prefix with the year and month to form a regularized ID, resets the serial number monthly through a Redis key expiration strategy, and ensures uniqueness under high concurrency by using a distributed lock. Specifically, as follows:
[0011] Configure the regular ID generation parameters in the Java backend system, including the business prefix (supports multiple business prefixes, such as "CG" for order business and "ZF" for payment business), the number of digits in the serial number (default 3 digits, supports configuration extension), and the year and month format ("yyyyMM").
[0012] Deploy a Redis cluster (master-slave + sentinel mode) to ensure high availability, and configure Redis connection pool parameters to ensure connection stability;
[0013] The business system initiates an ID generation request, carrying a business prefix parameter (such as "CG");
[0014] Retrieve the year and month string corresponding to the current date, and concatenate them into a Redis key in the format "id:seq:{business prefix}:{year and month}" (e.g., "id:seq:CG:202512"); where "year and month" is the current date in the format "yyyyMM";
[0015] The process of generating the sequence number corresponding to the current Redis key is locked by a distributed lock mechanism;
[0016] Execute a Redis atomic increment operation (INCR command) to obtain the current month's increment sequence number;
[0017] The incrementing sequence number is padded with zeros to make its length match the configured number of digits.
[0018] The final rule-based ID is formed by concatenating the characters according to the rule of "business prefix + year and month string + serial number after padding with zeros" (example format: CG202512001).
[0019] After the serial number is generated and the ID is concatenated, the distributed lock is released immediately. If the current Redis key does not have an expiration time set, an expiration time is set for the current Redis key (24 hours from 23:59:59 on the last day of the current month).
[0020] Return the rule-based ID to the business system; on the 1st of the following month, since the previous month's Redis key expired, a new Redis key was created and the sequence number 1 was returned when the Redis atomic auto-increment operation was executed for the first time, so as to realize the monthly reset of the sequence number.
[0021] As a preferred option, the lock key format of the distributed lock is "id:lock:{business prefix}:{year and month}", and the lock timeout is set to 3-5 seconds to avoid deadlock.
[0022] When acquiring a lock using the Redis SETNX command, the situation is as follows:
[0023] If the lock is successfully acquired, a Redis atomic increment operation (INCR command) is executed. Specifically: if the Redis key does not exist, the Redis atomic increment operation automatically creates it and returns 1; if the Redis key already exists, the incremented value (i.e., the current sequence number) is returned, ensuring that the sequence number is ordered and incremented.
[0024] If acquiring the lock fails, wait 100 milliseconds and retry. The number of retries will not exceed 3. If the number of retries exceeds 3, exception handling will be triggered.
[0025] More efficiently, zero padding is achieved through string formatting, as follows:
[0026] If the serial number is configured to have 3 digits, the serial number 1 will be "001" after being padded with zeros, the serial number 10 will be "010" after being padded with zeros, and the serial number 100 will be "100" after being padded with zeros.
[0027] If the serial number is less than the minimum value corresponding to the configured number of bits (e.g., a 3-bit serial number corresponds to 100), then add 0s before the serial number to ensure that the serial number length is uniform.
[0028] If the serial number exceeds the maximum number of digits configured (e.g., 3 digits correspond to 999), a serial number overflow exception is triggered, and an error message is returned (the business side needs to handle the scenario where the serial numbers for the current month are exhausted).
[0029] Even better, set the expiration time of Redis keys as follows: starting from 23:59:59 on the last day of the current month, set the expiration time to 24 hours to ensure that the key expires automatically on the 1st of the following month, and the serial number restarts from 001.
[0030] More preferably, the exception handling mechanism is as follows:
[0031] If the Redis connection fails, switch to the backup Redis node;
[0032] If all nodes are unavailable, the ID generation request is temporarily stored in the local message queue, and will be retried after Redis responds.
[0033] If the lock acquisition fails, the system will retry no more than 3 times and then return a "System busy, please try again later" error message to avoid indefinite waiting.
[0034] If the sequence number exceeds the maximum configured number of bits, a sequence number overflow exception will be triggered, the log will be recorded, and the operations and maintenance personnel will be notified to temporarily extend the number of bits or process the historical data archive.
[0035] More preferably, this method also includes cross-application consistency guarantees, as follows:
[0036] Multiple application instances in a distributed deployment share the same Redis cluster, ensuring global consistency in sequence number generation;
[0037] When the application starts, it checks whether the Redis key for the current year and month exists. If it does not exist, it initializes the sequence number to 0 (to avoid the first generation of the sequence number being abnormal due to the missing key).
[0038] A rule-based ID generation system for high-concurrency scenarios, the system comprising:
[0039] The ID rule configuration module is used to configure the fixed format of the rule-based ID, including the business prefix, the number of digits in the sequence number, and the year and month format.
[0040] The Redis sequence number generation module is used to interact with Redis, concatenate Redis keys, perform atomic auto-increment operations, and set key expiration times to achieve monthly increment and reset of sequence numbers. The Redis sequence number generation module is implemented based on a Redis cluster and supports sequence number sharing and consistency in a distributed environment.
[0041] The distributed lock module is used to lock the sequence number generation process in high-concurrency scenarios to avoid concurrent conflicts;
[0042] The ID concatenation module is used to concatenate the business prefix, year and month string, and zero-padded serial number into a final rule-based ID according to the rules.
[0043] The exception handling module is used to handle exception scenarios such as Redis connection failure, lock acquisition failure, and sequence number overflow.
[0044] As a preferred option, the distributed lock module acquires locks through the Redis SETNX command. The lock key corresponds one-to-one with the Redis sequence key (carrying the business prefix and year and month), ensuring that locks from different businesses and different months do not interfere with each other.
[0045] The exception handling module also includes a request caching submodule. The request caching submodule is used to temporarily store the ID generation request to the local message queue when the Redis cluster is unavailable. It will automatically retry after Redis recovers to avoid request loss.
[0046] The ID rule configuration module supports multi-service prefix configuration. Different services can independently configure the number of digits and format of the sequence number, enabling the parallel generation of multiple types of rule-based IDs in the same system.
[0047] An electronic device includes: a memory and at least one processor;
[0048] The memory stores computer-executed instructions;
[0049] The at least one processor executes the computer execution instructions stored in the memory, causing the at least one processor to execute the rule-based ID generation method in high-concurrency scenarios as described above.
[0050] A computer-readable storage medium storing computer-executable instructions, which, when executed by a processor, implement the rule-based ID generation method for high-concurrency scenarios as described above.
[0051] The method, system, device, and medium for generating regularized IDs in high-concurrency scenarios of the present invention have the following advantages:
[0052] (I) This invention adopts a fixed format of "business prefix + year and month + three-digit incrementing serial number" (e.g., CG202512001), and uses Redis's atomic auto-increment feature to achieve monthly serial number increment starting from 001. It ensures uniqueness and order under high concurrency through distributed locks and cache expiration strategies. It not only meets the requirements of custom rule format, but also has high concurrency processing capabilities, avoids serial number duplication or gaps, and is suitable for high-frequency business scenarios such as e-commerce and finance. It improves the reliability and efficiency of ID generation and is applicable to business systems that require rule-based IDs (such as order systems, payment transaction systems, logistics tracking systems, etc.). It aims to solve the problem of efficient and unique generation of rule-based IDs in high-concurrency scenarios.
[0053] (II) This invention aims to solve the problems of concurrency bottlenecks, duplicate serial numbers, inflexible formats, and inability to reset monthly in existing rule-based ID generation schemes. The specific objectives are as follows:
[0054] ① Implement a customizable ID format: Supports a fixed format of "business prefix + year and month + three-digit incrementing serial number" to meet the needs of visualizing business attributes, and can also meet the ID format requirements of different businesses without modifying the core logic;
[0055] ② Uniqueness guarantee under high concurrency: Based on Redis atomic auto-increment and distributed lock, it supports tens of thousands of concurrent requests per second, ensuring that IDs are not duplicated or conflicting, and is suitable for business scenarios such as e-commerce flash sales and high-frequency orders;
[0056] ③ Implement monthly serial number reset: The serial number is automatically reset to 001 on the 1st of each month through the Redis key expiration policy, without manual intervention or scheduled tasks, reducing operation and maintenance costs and meeting the business serial number cycle requirements;
[0057] ④ Improve ID generation efficiency: Reduce database interactions through Redis caching, control response time to the millisecond level, and adapt to high-concurrency business scenarios;
[0058] ⑤ Ensure high availability and fault tolerance: It has mechanisms such as Redis cluster switching, abnormal retry, and message queue temporary storage to avoid ID generation interruption or sequence number gap, and ensure stable system operation;
[0059] ⑥ High generation efficiency: Redis operation response time is in the millisecond range, and no database interaction is required. Compared with the database auto-increment solution, the ID generation efficiency is improved by more than 10 times.
[0060] ⑦ Strong distributed adaptability: Supports deployment scenarios with multiple application instances and multiple servers. By sharing the sequence number status through Redis, it ensures the consistency of global ID generation and solves the sequence number synchronization problem in a distributed environment. Attached Figure Description
[0061] The invention will be further described below with reference to the accompanying drawings.
[0062] Appendix Figure 1 This is a flowchart of a rule-based ID generation method for high-concurrency scenarios. Detailed Implementation
[0063] The following detailed description of the method, system, device, and medium for generating regular IDs in high-concurrency scenarios of the present invention is provided with reference to the accompanying drawings and specific embodiments.
[0064] Example 1:
[0065] As attached Figure 1As shown, this embodiment provides a method for generating regularized IDs in high-concurrency scenarios. This method generates monthly incrementing serial numbers based on Redis's atomic auto-increment feature, combines a business prefix with the year and month to form a regularized ID, and uses a Redis key expiration strategy to reset the serial number monthly. Combined with a distributed lock, it ensures uniqueness under high concurrency. Details are as follows:
[0066] S1. Configure the regular ID generation parameters in the Java backend system, including the business prefix (supports multiple business prefixes, such as "CG" for order business and "ZF" for payment business), the number of digits in the serial number (default 3 digits, supports configuration extension), and the year and month format ("yyyyMM").
[0067] S2. Deploy a Redis cluster (master-slave + sentinel mode) to ensure high availability, and configure Redis connection pool parameters to ensure connection stability;
[0068] S3. The business system initiates an ID generation request, carrying a business prefix parameter (such as "CG");
[0069] S4. Obtain the year and month string corresponding to the current date, and concatenate them into a Redis key in the format "id:seq:{business prefix}:{year and month}" (e.g., "id:seq:CG:202512"); where "year and month" is the current date in the format "yyyyMM";
[0070] S5. Lock the sequence number generation process corresponding to the current Redis key through a distributed lock mechanism;
[0071] S6. Execute the Redis atomic auto-increment operation (INCR command) to get the current month's increment sequence number;
[0072] S7. Pad the incrementing sequence number with zeros to make the length of the incrementing sequence number match the configured number of digits.
[0073] S8. Concatenate according to the rule of "business prefix + year and month string + serial number after padding with zeros" to form the final rule ID (format example: CG202512001);
[0074] S9. After the sequence number is generated and the ID is concatenated, immediately release the distributed lock. If the current Redis key does not have an expiration time set, then set an expiration time for the current Redis key (24 hours from 23:59:59 on the last day of the current month).
[0075] S10. Return the rule-based ID to the business system; where, on the 1st of the following month, because the Redis key expired in the previous month, a new Redis key is created and the sequence number 1 is returned when the Redis atomic auto-increment operation is executed for the first time, so as to realize the monthly reset of the sequence number;
[0076] S11. Cross-application consistency guarantee, as detailed below:
[0077] S101. Multiple application instances in a distributed deployment share the same Redis cluster to ensure global consistency in sequence number generation;
[0078] S102. When the application starts, check if the Redis key for the current year and month exists. If it does not exist, initialize the sequence number to 0 (to avoid the first generation of the sequence number being abnormal due to the missing key).
[0079] In this embodiment, the lock key format of the distributed lock is "id:lock:{business prefix}:{year and month}", and the lock timeout is set to 3-5 seconds to avoid deadlock.
[0080] In this embodiment, when acquiring the lock using the Redis SETNX command, the situation is as follows:
[0081] If the lock is successfully acquired, a Redis atomic increment operation (INCR command) is executed. Specifically: if the Redis key does not exist, the Redis atomic increment operation automatically creates it and returns 1; if the Redis key already exists, the incremented value (i.e., the current sequence number) is returned, ensuring that the sequence number is ordered and incremented.
[0082] If acquiring the lock fails, wait 100 milliseconds and retry. The number of retries will not exceed 3. If the number of retries exceeds 3, exception handling will be triggered.
[0083] In this embodiment, zero padding is implemented through string formatting, as follows:
[0084] If the serial number is configured to have 3 digits, the serial number 1 will be "001" after being padded with zeros, the serial number 10 will be "010" after being padded with zeros, and the serial number 100 will be "100" after being padded with zeros.
[0085] If the serial number is less than the minimum value corresponding to the configured number of bits (e.g., a 3-bit serial number corresponds to 100), then add 0s before the serial number to ensure that the serial number length is uniform.
[0086] If the serial number exceeds the maximum number of digits configured (e.g., 3 digits correspond to 999), a serial number overflow exception is triggered, and an error message is returned (the business side needs to handle the scenario where the serial numbers for the current month are exhausted).
[0087] In this embodiment, the expiration time of the Redis key is set as follows: starting from 23:59:59 on the last day of the current month, the expiration time is set to 24 hours to ensure that the key will automatically expire on the 1st of the following month, and the serial number will start counting again from 001.
[0088] The exception handling mechanism in this embodiment is as follows:
[0089] If the Redis connection fails, switch to the backup Redis node;
[0090] If all nodes are unavailable, the ID generation request is temporarily stored in the local message queue, and will be retried after Redis responds.
[0091] If the lock acquisition fails, the system will retry no more than 3 times and then return a "System busy, please try again later" error message to avoid indefinite waiting.
[0092] If the sequence number exceeds the maximum configured number of bits, a sequence number overflow exception will be triggered, the log will be recorded, and the operations and maintenance personnel will be notified to temporarily extend the number of bits or process the historical data archive.
[0093] In this embodiment, Redis atomic operations are guaranteed by leveraging the atomicity of the Redis INCR command to avoid duplicate sequence numbers in concurrent scenarios. The INCR command in Redis is executed in a single thread, so even if multiple requests are initiated simultaneously, the increment operations will be executed sequentially.
[0094] In this embodiment, the distributed lock is implemented based on the Redis SETNX command (setting it if it doesn't exist). The lock key carries a business prefix and year / month to ensure that locks from different businesses and different months do not interfere with each other. Example lock acquisition logic:
[0095] / / Distributed lock acquisition logic
[0096] public boolean tryLock(String lockKey,long expireTime){
[0097] String lockValue=uuID.randomuuID().tostring(); Boolean success=redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, expireTime, TimeUnit.SEcONDs); return Boolean.TRUE.equals(success):
[0098] / / Distributed lock release logic
[0099] public void releaseLock(String lockKey,String lockValue){StringcurrentValve=redisTemplate.opsForValue().get(lockKey);if(lockValve.equals(current Valve)){
[0100] redisTemplate.delete(lockKey);
[0101] }
[0102] }
[0103] In this embodiment, the month-year switching is handled automatically: on the 1st of the following month, since the Redis key of the previous month has expired, a new Redis key for the current month will be created when the ID is generated for the first time. The INCR operation returns 1, so that the serial number is automatically reset to 001 without the need for an additional scheduled task.
[0104] In this embodiment, the serial number padding utility class: implements fixed-length padding with zeros using String.format, and supports dynamic configuration of the serial number length. Example code:
[0105] / / Padding the serial number with zeros
[0106] public string fillzero(Long seq,int digit){String format="%"+digit+"d'return string.format(format,seq);
[0107] }
[0108] Example 2:
[0109] This embodiment provides a rule-based ID generation system for high-concurrency scenarios, the system comprising:
[0110] The ID rule configuration module is used to configure the fixed format of the rule-based ID, including the business prefix, the number of digits in the sequence number, and the year and month format.
[0111] The Redis sequence number generation module is used to interact with Redis, concatenate Redis keys, perform atomic auto-increment operations, and set key expiration times to achieve monthly increment and reset of sequence numbers. The Redis sequence number generation module is implemented based on a Redis cluster and supports sequence number sharing and consistency in a distributed environment.
[0112] The distributed lock module is used to lock the sequence number generation process in high-concurrency scenarios to avoid concurrent conflicts;
[0113] The ID concatenation module is used to concatenate the business prefix, year and month string, and zero-padded serial number into a final rule-based ID according to the rules.
[0114] The exception handling module is used to handle exception scenarios such as Redis connection failure, lock acquisition failure, and sequence number overflow.
[0115] In this embodiment, the distributed lock module acquires locks using the Redis SETNX command. The lock key corresponds one-to-one with the Redis sequence key (carrying the business prefix and year / month), ensuring that locks from different businesses and different months do not interfere with each other.
[0116] The exception handling module in this embodiment also includes a request staking submodule. The request staking submodule is used to temporarily store the ID generation request to the local message queue when the Redis cluster is unavailable, and automatically retry it after Redis recovers to avoid request loss.
[0117] The ID rule configuration module in this embodiment supports multi-service prefix configuration. Different services can independently configure the number of digits and format of the sequence number, realizing the parallel generation of multiple types of rule-based IDs in the same system.
[0118] The working process of this system is as follows:
[0119] (1) Initialize the Redis environment configuration, as follows:
[0120] a) Configure ID generation rules in the Java backend system: business prefix (supports multiple business prefixes, such as "CG" for order business and "ZF" for payment business), number of serial numbers (default 3 digits, supports configuration extension), and year / month format ("yyyyMM").
[0121] b) Deploy a Redis cluster (master-slave + sentinel mode) to ensure high availability, and configure Redis connection pool parameters to ensure connection stability;
[0122] (2) Redis key design and expiration policy configuration, as detailed below:
[0123] a) Design Redis key format: id:seq:{business prefix}:{year and month} (e.g., "id:seq:CG:202512"), where "year and month" is the current date in "yyyyMM" format;
[0124] b) Set an expiration time for Redis keys: Starting from 23:59:59 on the last day of the current month, the expiration time is set to 24 hours (ensuring that keys automatically expire on the 1st of the following month and the serial number starts counting again).
[0125] (3) The high-concurrency sequence number generation process is as follows:
[0126] a) The business system initiates an ID generation request, carrying a business prefix parameter (such as "CG");
[0127] b) The system retrieves the year and month string of the current date (e.g., "202512" corresponds to December 2025), and concatenates them to form a Redis key (e.g., "id:seq:CG:202512");
[0128] c) The distributed lock module attempts to acquire the lock (lock key format: id:lock:{business prefix}:{year and month}, lock timeout is 5 seconds to avoid deadlock);
[0129] d) If the lock is successfully acquired, execute the Redis atomic increment operation (INCR command): if the Redis key does not exist, INCR will automatically create it and return 1; if it already exists, return the incremented value (i.e., the current index);
[0130] e) If acquiring the lock fails, wait 100 milliseconds and retry. The number of retries shall not exceed 3. If the number of retries exceeds 3, exception handling shall be triggered.
[0131] (4) Serial number processing and ID concatenation, as detailed below:
[0132] a) Pad the auto-incrementing sequence number returned by Redis with zeros: If the sequence number is configured to be 3 digits, the sequence number 1 will be "001" after padding with zeros, the sequence number 10 will be "010" after padding with zeros, and the sequence number 100 will be "100" after padding with zeros.
[0133] b) If the serial number exceeds the maximum number of digits configured (e.g., 3 digits correspond to 999), a serial number overflow exception is triggered, and an error message is returned (the business side needs to handle the scenario where the serial number for the current month is exhausted).
[0134] c) Concatenate the ID according to the rules: business prefix + year and month string + serial number after padding with zeros (e.g., “CG” + “202512” + “001” → “CG202512001”);
[0135] (5) Lock release and cache maintenance, as detailed below:
[0136] a) After the serial number is generated and the ID is concatenated, immediately release the distributed lock (delete the lock key using the Redis DEL command); b) If the current Redis key does not have an expiration time set (e.g., when the serial number is generated for the first time), set an expiration time for it (23:59:59 + 24 hours on the last day of the current month);
[0137] (6) Exception handling mechanism, as follows:
[0138] a) Redis connection failure: Switch to a backup Redis node. If all nodes are unavailable, temporarily store the ID generation request in the local message queue and retry after Redis recovers.
[0139] b) Lock acquisition failed: Returns a "System busy, please try again later" message to avoid infinite waiting;
[0140] c) Sequence number overflow: Log the information and notify the operations and maintenance personnel. You can temporarily extend the number of digits of the sequence number or process the archiving of historical data.
[0141] (7) Cross-application consistency guarantee, as detailed below:
[0142] a) Multiple application instances in a distributed deployment share the same Redis cluster to ensure global consistency in sequence number generation;
[0143] b) When the application starts, check if the Redis key for the current year and month exists. If it does not exist, initialize the sequence number to 0 (to avoid the first generation of the sequence number being abnormal due to the missing key).
[0144] Example 3:
[0145] This embodiment also provides an electronic device, including: a memory and at least one processor;
[0146] The memory stores computer-executed instructions;
[0147] The at least one processor executes the computer execution instructions stored in the memory, causing the at least one processor to execute the regularized ID generation method in high-concurrency scenarios according to any one of the present invention.
[0148] The processor can be a central processing unit (CPU), or other general-purpose processors, digital signal processors (DSPs), application-specific integrated circuits (ASICs), off-the-shelf programmable gate arrays (FPGAs), or other programmable logic devices, discrete gate or transistor logic devices, discrete hardware components, etc. The processor can be a microprocessor or any conventional processor.
[0149] Memory is used to store computer programs and / or modules. The processor implements various functions of the electronic device by running or executing the computer programs and / or modules stored in the memory, and by accessing data stored in the memory. Memory can mainly include a program storage area and a data storage area. The program storage area can store the operating system, at least one application program required for a function, etc.; the data storage area can store data created based on the use of the terminal, etc. In addition, memory can also include high-speed random access memory, and can also include non-volatile memory, such as hard disks, RAM, plug-in hard disks, smart memory cards (SMC), secure digital cards (SD cards), flash memory cards, at least one disk storage device, flash memory device, or other volatile solid-state storage devices.
[0150] Example 4:
[0151] This embodiment also provides a computer-readable storage medium storing multiple instructions, which are loaded by a processor to cause the processor to execute the regularized ID generation method in a high-concurrency scenario according to any embodiment of the present invention. Specifically, a system or apparatus equipped with a storage medium may be provided, on which software program code implementing the functions of any of the above embodiments is stored, and the computer (or CPU or MPU) of the system or apparatus may read and execute the program code stored in the storage medium.
[0152] In this case, the program code read from the storage medium can itself implement the function of any of the above embodiments, and therefore the program code and the storage medium storing the program code constitute part of the present invention.
[0153] Examples of storage media used to provide program code include floppy disks, hard disks, magneto-optical disks, optical disks (such as CD-ROM, CD-R, CD-RW, DVD-ROM, DVD-RAM, DVD-RW, DVD+RW), magnetic tapes, non-volatile memory cards, and ROMs. Alternatively, program code can be downloaded from a server computer via a communication network.
[0154] Furthermore, it should be clear that not only can the program code read by the computer be executed, but also the operating system or other components operating on the computer can be instructed based on the program code to perform some or all of the actual operations, thereby realizing the function of any of the embodiments described above.
[0155] Furthermore, it is understood that the program code read from the storage medium is written to the memory set in the expansion board inserted into the computer or to the memory set in the expansion unit connected to the computer. Then, based on the instructions of the program code, the CPU or other components installed on the expansion board or expansion unit execute some and all of the actual operations, thereby realizing the function of any of the embodiments described above.
[0156] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention, and not to limit them; although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some or all of the technical features; and these modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the scope of the technical solutions of the embodiments of the present invention.
Claims
1. A method for generating rule-based IDs in high-concurrency scenarios, characterized in that, This method generates monthly incrementing sequence numbers based on Redis's atomic auto-increment feature, combines a business prefix with the year and month to form a regularized ID, and uses a Redis key expiration policy to reset the sequence number monthly. Combined with a distributed lock, it ensures uniqueness under high concurrency. Details are as follows: Configure the regular ID generation parameters in the Java backend system, including the business prefix, the number of digits in the sequence number, and the year / month format; Deploy a Redis cluster to ensure high availability, and configure Redis connection pool parameters to ensure connection stability; The business system initiates an ID generation request, carrying a business prefix parameter; Retrieve the year and month string corresponding to the current date, and concatenate them into a Redis key in the format "id:seq:{business prefix}:{year and month}"; where "year and month" is the current date in the format "yyyyMM"; The process of generating the sequence number corresponding to the current Redis key is locked by a distributed lock mechanism; Perform a Redis atomic increment operation to obtain the current month's increment sequence number; The incrementing sequence number is padded with zeros to make its length match the configured number of digits. The final standardized ID is formed by concatenating the elements according to the rule of "business prefix + year and month string + serial number after padding with zeros". After the sequence number is generated and the ID is concatenated, the distributed lock is released immediately. If the current Redis key does not have an expiration time set, then an expiration time is set for the current Redis key. Return the rule-based ID to the business system; on the 1st of the following month, since the previous month's Redis key expired, a new Redis key was created and the sequence number 1 was returned when the Redis atomic auto-increment operation was executed for the first time, so as to realize the monthly reset of the sequence number.
2. The method for generating regularized IDs in high-concurrency scenarios according to claim 1, characterized in that, The lock key format of the distributed lock is "id:lock:{business prefix}:{year and month}", and the lock timeout is set to 3-5 seconds to avoid deadlock. When acquiring a lock using the Redis SETNX command, the situation is as follows: If the lock is successfully acquired, a Redis atomic increment operation is executed. Specifically: if the Redis key does not exist, the Redis atomic increment operation automatically creates it and returns 1; if the Redis key already exists, the incremented value is returned. If acquiring the lock fails, wait 100 milliseconds and retry. The number of retries will not exceed 3. If the number of retries exceeds 3, exception handling will be triggered.
3. The method for generating regularized IDs in high-concurrency scenarios according to claim 1 or 2, characterized in that, Zero padding is achieved through string formatting, as follows: If the serial number is configured to have 3 digits, the serial number 1 will be "001" after being padded with zeros, the serial number 10 will be "010" after being padded with zeros, and the serial number 100 will be "100" after being padded with zeros. If the sequence number is less than the minimum value corresponding to the configured number of bits, add 0s before the sequence number to ensure that the sequence number length is uniform; If the sequence number exceeds the maximum configured bit length, a sequence number overflow exception is triggered, and an error message is returned.
4. The method for generating regularized IDs in high-concurrency scenarios according to claim 3, characterized in that, Set the expiration time for Redis keys as follows: starting from 23:59:59 on the last day of the current month, the expiration time is set to 24 hours.
5. The method for generating regularized IDs in high-concurrency scenarios according to claim 4, characterized in that, The exception handling mechanism is as follows: If the Redis connection fails, switch to the backup Redis node; If all nodes are unavailable, the ID generation request is temporarily stored in the local message queue, and will be retried after Redis responds. If the lock acquisition fails, the system will retry no more than 3 times and then return an error message: "System busy, please try again later". If the sequence number exceeds the maximum configured number of bits, a sequence number overflow exception will be triggered, the log will be recorded, and the operations and maintenance personnel will be notified to temporarily extend the number of bits or process the historical data archive.
6. The method for generating regularized IDs in high-concurrency scenarios according to claim 5, characterized in that, This method also includes cross-application consistency guarantees, as detailed below: Multiple application instances in a distributed deployment share the same Redis cluster, ensuring global consistency in sequence number generation; When the application starts, it checks if the Redis key for the current year and month exists; if it does not exist, it initializes the sequence number to 0.
7. A rule-based ID generation system for high-concurrency scenarios, characterized in that, The system includes: The ID rule configuration module is used to configure the fixed format of the rule-based ID, including the business prefix, the number of digits in the sequence number, and the year and month format. The Redis sequence number generation module is used to interact with Redis, concatenate Redis keys, perform atomic auto-increment operations, and set key expiration times to achieve monthly increment and reset of sequence numbers. The Redis sequence number generation module is implemented based on Redis cluster and supports sequence number sharing and consistency in a distributed environment. The distributed lock module is used to lock the sequence number generation process in high-concurrency scenarios to avoid concurrent conflicts; The ID concatenation module is used to concatenate the business prefix, year and month string, and zero-padded serial number into a final rule-based ID according to the rules. The exception handling module is used to handle exception scenarios such as Redis connection failure, lock acquisition failure, and sequence number overflow.
8. The rule-based ID generation system for high-concurrency scenarios according to claim 7, characterized in that, The distributed lock module acquires locks using the Redis SETNX command. The lock key corresponds one-to-one with the Redis sequence key, ensuring that locks from different businesses and different months do not interfere with each other. The exception handling module also includes a request caching submodule. The request caching submodule is used to temporarily store the ID generation request to the local message queue when the Redis cluster is unavailable. It will automatically retry after Redis recovers to avoid request loss. The ID rule configuration module supports multi-service prefix configuration. Different services can independently configure the number of digits and format of the sequence number, enabling the parallel generation of multiple types of rule-based IDs in the same system.
9. An electronic device, characterized in that, include: Memory and at least one processor; The memory stores computer-executed instructions; The at least one processor executes the computer execution instructions stored in the memory, causing the at least one processor to perform the rule-based ID generation method in a high-concurrency scenario as described in any one of claims 1 to 6.
10. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores computer-executable instructions, which, when executed by the processor, implement the rule-based ID generation method in a high-concurrency scenario as described in any one of claims 1 to 6.