The use Redis increment incr implement to achieve order number

How to generate a unique order serial number?
In accordance with the format: yyyyMMdd + +10 two service code bits increment sequence,
such as 0000000001 20150101 ** 99 **.

Ideas:
1. Obtain date very simple;
2 service code is passed to invoke the service parameters;
3. 10 Redis achieved stored sequence and a self-energizing self-energizing, using serial.number: {} date format save value increment sequence of a given day;

Directly on the code:

first step:

public  class of StringUtil { 
    
    static  Final  int DEFAULT_LENGTH = 10 ; 

    / ** 
     * get 10-bit serial number, a length of less than 10, up the front 0 
     * 
     * @param SEQ 
     * @return 
     * / 
    public  static String of the getSequence ( Long SEQ) { 
        String STR = String.valueOf (SEQ);
         int len = str.length ();
         IF (len> = DEFAULT_LENGTH) { // depending on the scale of business, should not reach the 10 
            return STR; 
        } 
        int REST = DEFAULT_LENGTH - len;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < rest; i++) {
            sb.append('0');
        }
        sb.append(str);
        return sb.toString();
    }

}

Step two:

   public Long incr(String key, long liveTime) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();
        if ((null == increment || increment.longValue() == 0) && liveTime > 0) {//初始设置过期时间
            entityIdCounter.expire(liveTime, TimeUnit.HOURS);
        }
        return increment;
    }

Supplementary: incr is from zero, if necessary from the beginning, need more time, here needs a start. There is a pit because it is five digits, so there is no need to go to the number of bits filled with zeros.

third step:

@Service
public class SerialNumberService {

    @Resource
    private RedisDao redisDao;
//生成导入批次号 private String getOrder() { String order = ""; String dateString = DateUtils.formatDate(new Date()); Long incr = redisComponent.incr("deviceRepair" + dateString, 24); if (incr == 0) { incr = redisComponent.incr("deviceRepair" + dateString, 24); } DecimalFormat df = new DecimalFormat("00000"); String[] drs = dateString.split("-"); for (int i = 1; i < drs.length; i++) { order += drs[i]; } order = "X" + order + df.format(incr); return order; }

Guess you like

Origin www.cnblogs.com/ZJOE80/p/12181759.html