A scenario in which a unique coupon code needs to be generated is encountered in the project. There are two schemes for generating voucher codes:
A. Generate a batch of coupon code in advance (the field in the database to add a unique index), so that the uniqueness of the coupon code, through the background script pre-determined that the number of coupon code is less than a certain value, re-generate a batch of coupon code
B. In combination with Redis scheme, using Redis to set up cursors, take eight-bit coupon code as an example, find out the maximum eight-bit prime number, and then through the prime number algorithm and cursors to calculate the eight-bit coupon code, but this method does not guarantee that the uniqueness of the coupon code may appear duplicate
A programme can guarantee the uniqueness but the maintenance of the difficulty B scheme cannot guarantee uniqueness
Do you have any good algorithms to recommend?
Reply content:
A scenario in which a unique coupon code needs to be generated is encountered in the project. There are two schemes for generating voucher codes:
A. Generate a batch of coupon code in advance (the field in the database to add a unique index), so that the uniqueness of the coupon code, through the background script pre-determined that the number of coupon code is less than a certain value, re-generate a batch of coupon code
B. In combination with Redis scheme, using Redis to set up cursors, take eight-bit coupon code as an example, find out the maximum eight-bit prime number, and then through the prime number algorithm and cursors to calculate the eight-bit coupon code, but this method does not guarantee that the uniqueness of the coupon code may appear duplicate
A programme can guarantee the uniqueness but the maintenance of the difficulty B scheme cannot guarantee uniqueness
Do you have any good algorithms to recommend?
timestamp, random number, hash function, user information (such as user ID, requested IP, etc.) ...
See the specific situation, combined with, the basic can be achieved each time the generated coupon code is not duplicated.
If the requirements are relatively high, you can build a table, build a unique index, and then try inserting it to verify that you are repeating it.
(If you repeat, regenerate the random number and recalculate the build once.) )
In advance of what, code complex, and tease, or need to calculate the real time is better.
Something about time is going to be the only thing.
You can use Redis's self-increment operation, which is atomic and does not repeat; if it's longer, it's a UUID.