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