zoukankan      html  css  js  c++  java
  • 基于redis 生成唯一订单号

    烦恼的唯一订单号= =、借助于redis锁

    定义场景:laravel  php

    /**
         * @param string $key redisKey
         * @param int $length 字符串长度
         * @param string $prefix 字符串前缀
         * @param bool $useEn 是否可用英文
         * @return string
         */
        function get_unique_order_no(string $key, int $length, string $prefix = '', bool $useEn = false): string
        {
            $key = $key . '_' . date('Ymd');
            $redis = Redis::connection();
            $redisLock = new IlluminateCacheRedisLock($redis, $key . '_lock', 30);
            try {
                $redisNum = $redisLock->block(5, function () use ($key) {
                    if (Redis::ttl($key) < 0) {
                        $time = strtotime(date("Y-m-d", time())) + 60 * 60 * 24 - strtotime(date("Y-m-d H:i:s", time()));
                        Redis::expire($key, $time);
                    }
                    Redis::incr($key);
                    return Redis::get($key);
                });
                $string = $prefix . date('ymdHi');
                if ($useEn) {
                    $redisNum = dechex($redisNum);
                } else {
                    $redisNum = decoct($redisNum);
                }
                $len = $length - strlen($redisNum);
                $leftStrLen = $len - strlen($string);
                if ($leftStrLen >= 0) {
                    $string = str_pad($string, $len, 0, STR_PAD_RIGHT);
                } else {
                    $string = substr($string, 0, $len);
                }
                return $string . $redisNum;
            } catch (Throwable $e) {
                return substr($prefix . date('ymd') . hexdec(uniqid()), 0, $length);
            }
        }
    

      代码暂时解决了我的问题,后面有情况再做调整

      博客唯一地址:https://www.cnblogs.com/pfdltutu/p/15080887.html,转载请注明出处

  • 相关阅读:
    文件查找和比较命令 来自: http://man.linuxde.net/find
    Docker学习计划
    Mybatis各种模糊查询
    linux下vi命令大全
    mac下的环境变量
    slf4j输出变量
    使用lombok中的log
    idea中的java web项目(添加jar包介绍)和java maven web项目目录结构
    slf4j+logback&logback.xml
    日志框架
  • 原文地址:https://www.cnblogs.com/pfdltutu/p/15080887.html
Copyright © 2011-2022 走看看