默认引入了redis依赖,这里就不上依赖了。

这里需要的是生成一个huize20171027100140000001这种格式的字符串,可以看到前面大致是字符串+年月日时间分秒毫秒+三位自增num

接单表述一下基本思路:
这里先用时间(年月日)生成一个key,然后,利用RedisAtomicLongincrementAndGet方法调用redisINCR原子加,之后给这个key设置一个24小时+随机数的过期时间,最后获取的INCR结果再对999进行取余,使得最终获取的结果肯定是小于999的,因为只需要三位数

 @Test
public void testMd5(){
    String str = getTransNo("huize");
    String sign = DigestUtils.md5DigestAsHex(str.getBytes()).toLowerCase();
}

//channel 渠道
public String getTransNo(String channel){
    LocalDateTime nowTime = LocalDateTime.now();
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
    String dateStr = dateTimeFormatter.format(nowTime);

    DateTimeFormatter inceKeyFormat = DateTimeFormatter.ofPattern("yyyy:MM:dd");
    String formatMinute = inceKeyFormat.format(nowTime);
    String key = formatMinute;

    Double randExpireTime = Math.floor(Math.random() * 10) + 24;

/*        Long increment = redisTemplate.opsForValue().increment(key, 1l);
    Long expire = redisTemplate.boundValueOps(key).getExpire();
    System.out.println(expire);

    Boolean aBoolean = redisTemplate.boundValueOps(key).expireAt(new Date(System.currentTimeMillis() + 10000));
    redisTemplate.boundValueOps(key).expire(1,TimeUnit.MINUTES);*/

    org.springframework.data.redis.support.atomic.RedisAtomicLong atomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
    Long incrementAndGet = atomicLong.incrementAndGet();
    Long expire1 = atomicLong.getExpire();
    System.out.println(expire1);
    atomicLong.expire(randExpireTime.longValue(), TimeUnit.HOURS);
    expire1 = atomicLong.getExpire();
    System.out.println(expire1);


/*        for (int i = 0; i < 9; i++) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                RedisAtomicLong atomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
                Long incrementAndGet = atomicLong.incrementAndGet();
                System.out.println(incrementAndGet);
                Long expire1 = atomicLong.getExpire();
                System.out.println(expire1);
                atomicLong.expire(randExpireTime.longValue(), TimeUnit.MINUTES);
                expire1 = atomicLong.getExpire();
                System.out.println(expire1);
            }
        });
        thread.start();
    }*/

    int incrementResult = incrementAndGet.intValue() % 999;

    String incrementStr = String.format("%03d", incrementResult);
    //生成格式为:渠道名称拼音小写+随机字符串,长度为25位,如慧择:huize20171027100140000001
    System.out.println(channel + dateStr + incrementStr);
    return  channel + dateStr + incrementStr;
}

huize20210830105239720015

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐