thinkphp5.1使用redis

1.安装redis ,并启动redis服务

2.安装php redis 拓展

3.在redis.php中添加配置

<?php

return [
    'host' => '127.0.0.1',
    'port' => '6379',
];

在根目录extend里新建redis目录,并在其里面建Redis.php文件,文件内容如下:

<?php

namespace redis;


class Redis extends \Redis
{
    public static function redis() {
        $con = new \Redis();
        $con->connect(config('redis.host'), config('redis.port'), 5);
        return $con;
    }
}

在项目根目录thinkphp目录里helper.php里设置redis助手函数,加入如下内容:

if (!function_exists('redis')) {
    /**
     * 获取容器对象实例
     * @return Container
     */
    function redis()
    {
        return \redis\Redis::redis();
    }
}

在控制器里使用

  public function index()
    {
        redis()->set('task_num_1',3);
        $num = redis()->get('task_num_1');
        halt($num);
        return $this->fetch();
    }

猜你喜欢

转载自www.cnblogs.com/zhangyouwu/p/12663989.html