它山之石可以攻玉

键盘上的生活
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

PHP基于Redis的全局订单号id

Posted on 2020-04-22 10:16  陈达辉  阅读(501)  评论(0编辑  收藏  举报
<?php
/**
 * 基于Redis的全局订单号id
 *
 * @author chendahui
 **/

namespace site\library;

class OrdersNum {

    private $_r;
    private $_host;
    private $_port;
    private $_passwd;
    private $_prefix;
    private $_len;

    function __construct() {

        try {

            $redisconfig = array(
                'host'     => REDIS_HOST,
                'port'     => REDIS_PORT,
                'password' => REDIS_PASSWORD,
                'prefix'   => 'CB',
                'len'      => 3,
            );

            $this->setBuilder($redisconfig);

            $this->_r = new \Redis();
            $ret = $this->_r->connect($this->_host, $this->_port);
            if (!$ret) {
                die("[redis connect error]");
            }
            $this->_r->auth($this->_passwd);
        }
        catch (Exception $e) {
            trace($e->getMessage());
        }
    }

    private function setBuilder($redisconfig) {

        $this->_host   = $redisconfig['host'];
        $this->_port   = $redisconfig['port'];
        $this->_passwd = $redisconfig['password'];
        $this->_prefix = $redisconfig['prefix'];
        $this->_len    = $redisconfig['len'];
    }

    /**
     * 生成当天全局唯一自增id
     *
     * @param integer $key
     *
     * @return $id
     * @author chendahui
     **/
    private function nextId($key) {
        $id = $this->_r->incr($this->_prefix.":".$key);
        $l = strlen($id);
        if ($l>$this->_len) {
            return $id;
        } else {
            return str_repeat(0, $this->_len-$l).$id;
        }
    }

    /**
     * 获取订单号
     *
     * @return integer
     * @author chendahui
     **/
    public function getOrdersNum() {

        $key = date('Ymd', time());
        return $this->_prefix.$key.$this->nextId($key);
    }
}