• 【redis 封装】


    <?php
    /**
     * Created by PhpStorm.
     * User: andy
     * Date: 18/3/26
     */
    namespace appcommonlib
    edis;
    class Predis {
        public $redis = "";
        /**
         * 定义单例模式的变量
         * @var null
         */
        private static $_instance = null;
    
        public static function getInstance() {
            if(empty(self::$_instance)) {
                self::$_instance = new self();
            }
            return self::$_instance;
        }
    
        private function __construct() {
            $this->redis = new Redis();
            $result = $this->redis->connect(config('redis.host'), config('redis.port'), config('redis.timeOut'));
            if($result === false) {
                throw new Exception('redis connect error');
            }
        }
    
        /**
         * set
         * @param $key
         * @param $value
         * @param int $time
         * @return bool|string
         */
        public function set($key, $value, $time = 0 ) {
            if(!$key) {
                return '';
            }
            if(is_array($value)) {
                $value = json_encode($value);
            }
            if(!$time) {
                return $this->redis->set($key, $value);
            }
    
            return $this->redis->setex($key, $time, $value);
        }
    
        /**
         * get
         * @param $key
         * @return bool|string
         */
        public function get($key) {
            if(!$key) {
                return '';
            }
    
            return $this->redis->get($key);
        }
    
        /**
         * @param $key
         * @return array
         */
        public function sMembers($key) {
            return $this->redis->sMembers($key);
        }
    
        /**
         * @param $name
         * @param $arguments
         * @return array
         */
        public function __call($name, $arguments) {
            //echo $name.PHP_EOL;
            //print_r($arguments);
            if(count($arguments) != 2) {
                return '';
            }
            $this->redis->$name($arguments[0], $arguments[1]);
        }
    }

    总结:采用单例模式:减少资源不必要开销

  • 相关阅读:
    php && 逻辑与运算符使用说明
    php无穷递归算法
    PHP foreach 用法
    centos安装g++
    php 编译中apxs
    shutdown()
    C语言strtok()函数:字符串分割
    细谈select函数(C语言)
    setsockopt的作用
    STL之七:STL各种容器的使用时机详解
  • 原文地址:https://www.cnblogs.com/fyandy/p/10061329.html
Copyright © 2020-2023  润新知