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