基于redis创建订单号
1.引入redis密码
@Value("${spring.redis.password}") private String redisPassword;
2.示例
Orders orders = new Orders();orders.setOrdersNo(OrderNumberGeneratorUtils.generateOrderNumber(redisPassword));orders.setOpenId(openId);orders.setGoodsId(goodsId);orders.setPoints(goods.getPrice());ordersService.save(orders);
3.工具类
import redis.clients.jedis.Jedis;import java.text.SimpleDateFormat;
import java.util.Date;/** 生成订单号* @ClassName: OrderNumberGenerator* @Description:* @Author: zhangxiaohui* @Date: 2025-01-10* @Version: 1.0**/
public class OrderNumberGeneratorUtils {private static final String SEQUENCE_KEY = "check_sequence"; // Redis 中保存序列号的键名private static final String REDIS_HOST = "localhost";private static final int REDIS_PORT = 6379;public static synchronized String generateOrderNumber(String REDIS_PASSWORD) {// 获取当前日期,格式为YYYYMMDDString datePart = getFormattedDate();// 格式化序列号,补零至三位数(例如,001)String sequencePart = String.format("%03d", getNextSequence(REDIS_PASSWORD));return datePart + sequencePart;}private static String getFormattedDate() {SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");return dateFormat.format(new Date());}private static int getNextSequence(String REDIS_PASSWORD) {try (Jedis jedis = new Jedis(REDIS_HOST, REDIS_PORT)) {jedis.auth(REDIS_PASSWORD); // 提供密码进行连接Long nextSequence = jedis.incr(SEQUENCE_KEY);if (nextSequence > 999) {jedis.del(SEQUENCE_KEY); // 重置序列号return 0;}return nextSequence.intValue();} catch (Exception e) {e.printStackTrace(); // 处理 Redis 连接或操作异常return 0;}}/*** 删除redis中的key*/public static boolean deleteKey(String REDIS_PASSWORD) {try (Jedis jedis = new Jedis(REDIS_HOST, REDIS_PORT)) {jedis.auth(REDIS_PASSWORD); // 提供密码进行连接jedis.del(SEQUENCE_KEY); // 删除指定的键System.out.println("Key '" + SEQUENCE_KEY + "' deleted successfully from Redis.");return true;} catch (Exception e) {e.printStackTrace(); // 处理 Redis 连接或操作异常}return false;}public static void main(String[] args) {//生成订单编号System.out.println(generateOrderNumber("123456"));}