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);
    }

}

猜你喜欢

转载自blog.csdn.net/qq_17040587/article/details/84031871