通过PHP面向对象方式操作redis

<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Request;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
    public static $redis = false;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$redis = $this->getRedis();
    }

    public function index()
    {
        $id = $_GET['id'] ?? 1;
        $id = 'id_' . $id;

        $num = self::$redis->exists($id) ? self::$redis->get($id) : self::$redis->set($id, 1);
        $num++;
        self::$redis->set($id, $num);
        echo self::$redis->get($id);
    }

    private function getRedis()
    {
        if (self::$redis) {
            return self::$redis;
        } else {
            $redis = new \Redis();
            $redis->connect('127.0.0.1', 6379);
            return $redis;
        }
    }


}

最后编辑于:2019/12/25作者: 牛逼PHP

发表评论