zoukankan      html  css  js  c++  java
  • PHP基于Redis的全局订单号id

    <?php
    /**
     * 基于Redis的全局订单号id
     *
     * @author chendahui
     **/
    
    namespace sitelibrary;
    
    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);
        }
    }
    

      

  • 相关阅读:
    《人月神话》阅读笔记02
    《人月神话》阅读笔记01
    第十四周学习进度条
    我们做的作品 请大家多多支持我们
    Beta阶段项目总结
    Alpha阶段项目总结
    Alpha版总结会议
    站立会议10(第二次冲刺)
    站立会议09(第二次冲刺)
    站立会议08(第二次冲刺)
  • 原文地址:https://www.cnblogs.com/tdalcn/p/12750233.html
Copyright © 2011-2022 走看看