4.同步redis的多次調用 防止多次創建redis實例化鏈接類

首先有php環境 redis服務
然後php支持redis的拓展安裝 類似的(https://blog.csdn.net/qq_17040587/article/details/83992659) 介紹的操作。不同是,redis的服務沒有在php安裝包的ext裏面,需要去php的官方下載對應的拓展下載。然後鏈接內的教程類似安裝。這裏參照即可,有不明白的小夥伴可以留言,就不在講步驟了。
然後,一個驗證碼登錄過程,我們藉助redis來覈對驗證碼是否正確,如果正確,讓redis來幫我保存登錄信息。這裏就會有多次調用redis的操作,反覆使用,必須防止重複鏈接reids浪費資源哦!
這裏是一個redis優化的方法:

<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 18-11-13
 * Time: 下午4:01
 */
namespace  app\common\lib\redis;

class Predis{


    private  static $_instance= null;

    /**
     * @return Predis|null
     * @throws \Exception
     */
    public static  function getInstance(){
        if(empty(self::$_instance)){
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * Predis constructor.
     * @throws \Exception
     */
    private function __construct()
    {
        $this->redis = new \Redis();

        $result  = $this->redis->connect(config('redis.host'),config('redis.port'),config('redis.con_out'));
        if($result===false){
            throw  new \Exception('redis connect error');
        }
    }

    /**
     * redis 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);
    }

    /**
     * redis get
     * @param $key
     * @return bool|string
     */
    public function  get($key){
        if(!$key){
            return '';
        }
        return $this->redis->get($key);
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章