美文网首页
thinkphp 连接redis 2022-04-06

thinkphp 连接redis 2022-04-06

作者: 阿然学编程 | 来源:发表于2022-04-05 12:47 被阅读0次
    //php需要安装redis扩展,并且是开启状态
    public function index()
    {
        //连接Redis
        $redis = new \Redis();
        $redis->connect('127.0.0.1', '6379');
        $redis->auth('root');
        //操作Redis
        $redis->set('k1','v1');//设置key
        $get = $redis->get('k1');//获取k1的值
        dump($get);
    }
  • 单例封装
class Redismeans
{

    /**
     * 本地保存的单例
     * @var unknown
     */
    private static $instance = null;

    /**
     * 本地保存的Redis实例
     * @var object
     */
    private static $redis;

    //Host(必填)
    private $host = '127.0.0.1';
    //Port(必填)
    private $port = 6379;
    //Password(必填)
    private $pass = '';

    //防止直接创建对象
    private function __construct()
    {
        self::$redis = new \Redis();
        //连接redis
        self::$redis->connect($this->host, $this->port);
        if ($this->pass) {
            self::$redis->auth($this->pass);
        }
    }

    //防止克隆对象
    private function __clone()
    {
         //TODO: Implement __clone() method
    }

    //单一获取对象入口
    public static function getRedis()
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self;
        }
        return self::$redis;
    }

}

相关文章

网友评论

      本文标题:thinkphp 连接redis 2022-04-06

      本文链接:https://www.haomeiwen.com/subject/zqprsrtx.html