方案1 :使用redis的incr自增实现唯一序号,
实现1
private static String QUOTATION_PREFIX = "BJD";private static String QUOTATION_INIT = "0000";public String generateQuotationNumber() {//格式:T+yyyyMMdd+4位流水StringBuffer sbuffer = new StringBuffer();sbuffer.append(QUOTATION_PREFIX);SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");sbuffer.append(sdf.format(new Date())); // 拼接好流水号的前缀String incKey = sbuffer.toString();String no = incr(incKey, 1);sbuffer.append(no);return sbuffer.toString();}public String incr(String key, long liveTime) {// 基于这个key创建一个redis的值,默认的value为0RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, stringRedisTemplate.getConnectionFactory());// 对于这个key进行自增1的操作 然后返回自增1 之前的数据Long increment = entityIdCounter.getAndIncrement();// 如果为0 则是第一次创建这个可以,则设置这个key的过期时间为1天if ((null == increment || increment.longValue() == 0) & liveTime > 0) {//初始设置过期时间entityIdCounter.expire(liveTime, TimeUnit.DAYS); //设置自增值过期时间,liveTime 过期时间;TimeUnit.DAYS 过期时间单位,我这边设置为天}// 拿到这个key进行操作,组合出满足要求的数据if (increment == 0) {increment = increment + 1;} else if (increment > 9999) {increment = 1L;}//位数不够,前面补0DecimalFormat df = new DecimalFormat(QUOTATION_INIT);return df.format(increment);}
代码详解
stringRedisTemplate.getConnectionFactory() 返回redis的生成工厂

RedisAtomicLong在创建的时候,会基于这个key在redis创建一个键值对,初始value为0,


getAndIncrement 最终调用的是increment方法,对这个键进行+1操作,返回返回值进行-1,这样就对redis的值进行了自增,返回自增之前的值
