/** * 生成订单编号:站点编号前三位 + [5,12]位自增编号 * * @param siteCode * @return * @author jqlin */ private String getOrderNo(String siteCode) { String result = siteCode.length() <= 3 ? siteCode : siteCode.substring(0, 3); result = result.toUpperCase(); try { String orderNoIncr = "orderNoIncr"; if(!RedisUtil.exists(orderNoIncr)) { RedisUtil.set(orderNoIncr, "0"); } //根据redis生成自增ID Long seq = RedisUtil.incr(orderNoIncr); if(seq == null || seq == 0L) { //根据mysql生成自增ID seq = (Long)idDao.save(new IdModel()); result = result + "DB" + Util.getSequence(seq); } else { result = result + Util.getSequence(seq); } } catch (Exception e) { //根据内存生成自增ID result = result + "MM" + String.valueOf(Math.abs(UUID.randomUUID().getMostSignificantBits())).substring(0, 8); } return result; }
/** * 自增编号范围在[10000,999999999999],不足补0 * * @param seq * @return * @author jqlin */ public static String getSequence(long seq) { long defaultLength = 9999L; long maxLength = 999999999999L; if(seq >= maxLength) { return String.valueOf(maxLength); } if(seq > defaultLength) { return String.valueOf(seq); } int len = 5 - String.valueOf(seq).length(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { sb.append('0'); } sb.append(seq); return sb.toString(); }