zoukankan      html  css  js  c++  java
  • 【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]);
        }
    }

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

  • 相关阅读:
    12-五子棋游戏:享元模式
    11-制作糖醋排骨:外观模式
    10-蒸馒头:装饰者模式
    09-公司层级结构:组合模式
    08-开关与电灯:桥接模式
    07-电源转换:适配器模式
    将博客搬至CSDN
    iview和element中日期选择器快捷选项的定制控件
    详解AJAX工作原理以及实例讲解(通俗易懂)
    最全肌肉锻炼动图
  • 原文地址:https://www.cnblogs.com/fyandy/p/10061329.html
Copyright © 2011-2022 走看看