Spring boot Redis Self-increment number control pit

Source: Internet
Author: User

In the near term, the company took over a order number generation service, the rules have been set by the project manager, they are the main number of the following four-digit representative of the current order number has been executed the first few. And there is a requirement to support the distributed. In order to achieve this, I started using Redis's incr to solve this problem, because our backend development uses spring boot, so I found a code like this online:

1 /**2      *3      * @paramKey4      * @paramLivetime5      * @return6      */7      PublicLong incr (String key,Longlivetime) {8Redisatomiclong Entityidcounter =NewRedisatomiclong (Key, Redistemplate.getconnectionfactory ());9Long increment =entityidcounter.getandincrement ();Ten  One         if((NULL= = Increment | | Increment.longvalue () = = 0) && livetime > 0) {//Initial set Expiration time A Entityidcounter.expire (Livetime, timeunit.seconds); -         } -  the         returnincrement; -}

Results test, look at the back of the number is very satisfied, the heart is a little bit excited oh ~ ~

But when I sort the data from small to large, I find a bit strange, that the first few are problematic.

So through the test found that, when the Redis has not set a timer in the flash, distributed services, there will be a number of previous duplication phenomenon.

After discovering the problem, I passed the Redis lock, and when I judged that there was no count key under Redis, locked it, and then locked it, the other person came in when the call, the thread slept 500ms, and then went down. Smooth Solution ~ ~ ~

Spring boot Redis Self-increment number control pit

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.