• 根据redis自增生成全局唯一订单id


    package com.example.springbootshardingjdbc.util;
    
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    
    public class MyUtil {
        public static String currentDateTime(){
            LocalDateTime localDateTime=LocalDateTime.now();
            DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            String now = dateTimeFormatter.format(localDateTime);
            return now;
        }
    
        /**
         * 根据自增id生成唯一订单号
         * @param incrKey 自增id
         * @return
         */
        public static String renderOrderId(Long incrKey){
            /**
             * 日期+00001 后边是5位数 补零
             */
            String orderId = currentDateTime() + String.format("%1$05d", incrKey);
            return orderId;
        }
    
        public static void main(String[] args) {
            String result = renderOrderId(2L);
            System.out.println(result);
        }
    
    }



    调用:

    可根据项目实际情况确定订单号的位数,一般日期到秒足以支撑绝大部分系统

       @RequestMapping("/generateOrderId")
        public Object generateOrderId(String userName){
            Long result = redisTemplate.opsForValue().increment(userName);
            String orderId = MyUtil.renderOrderId(result);
            System.out.println(userName+":"+orderId);
            return orderId;
        }
    
    
    结果:
    lisi:2020022416433100214
    lisi:2020022416433100215
    lisi:2020022416433100216
    lisi:2020022416433100217
    lisi:2020022416433100218
    lisi:2020022416433200219
    lisi:2020022416433200220
    lisi:2020022416433200221
    lisi:2020022416433200222
    lisi:2020022416433200223
    lisi:2020022416433200224
    lisi:2020022416433300225
    lisi:2020022416433300226
    lisi:2020022416433300227
    lisi:2020022416433300228
    lisi:2020022416433300229
    lisi:2020022416433300230
    lisi:2020022416433400231
    lisi:2020022416433400232
    lisi:2020022416433400233
    lisi:2020022416433400234
    lisi:2020022416433400235
    lisi:2020022416433400236
    wangwu:2020022416435300001
    wangwu:2020022416435400002
    wangwu:2020022416435500003
    wangwu:2020022416435500004
    wangwu:2020022416435500005
    wangwu:2020022416435500006
    wangwu:2020022416435500007
    wangwu:2020022416435500008
    wangwu:2020022416435600009
    wangwu:2020022416435600010
  • 相关阅读:
    JetBrains——账户登录错误(JetBrains Account Error:JetBrains Account connection error: www.jetbrains.com)解决方案
    pip list出错原因
    MyBatis 动态SQL
    MyBatis Mapper文件简述
    MyBatis XML配置
    MyBatis 简单笔记
    nginx配置文件参考
    CentOS 8 下 nginx 服务器安装及配置笔记
    CentOS8 下 Redis5.0.7 哨兵Sentinel 模式配置指南
    shell script简单笔记
  • 原文地址:https://www.cnblogs.com/coderdxj/p/12357609.html
Copyright © 2020-2023  润新知