easyswoole框架之Redis使用

利用composer安装redis协程客户端

可直接安装redis-pool组件实现连接池:

composer require easyswoole/redis-pool

安装 easyswoole/pool 组件自定义实现:

composer require easyswoole/pool

在这里插入图片描述
安装完以后在

新增文件/App/Pool/RedisPool.php

<?php
/**
 * Created by PhpStorm.
 * User: Tioncico
 * Date: 2019/10/15 0015
 * Time: 14:46
 */

namespace App\Pool;

use EasySwoole\Pool\Config;
use EasySwoole\Pool\AbstractPool;
use EasySwoole\Redis\Config\RedisConfig;
use EasySwoole\Redis\Redis;

class RedisPool extends AbstractPool
{
    protected $redisConfig;

    /**
     * 重写构造函数,为了传入redis配置
     * RedisPool constructor.
     * @param Config      $conf
     * @param RedisConfig $redisConfig
     * @throws \EasySwoole\Pool\Exception\Exception
     */
    public function __construct(Config $conf,RedisConfig $redisConfig)
    {
        parent::__construct($conf);
        $this->redisConfig = $redisConfig;
    }

    protected function createObject()
    {
        //根据传入的redis配置进行new 一个redis
        $redis = new Redis($this->redisConfig);
        return $redis;
    }
}

在这里插入图片描述
在dev.php中配置redis连接配置
在这里插入图片描述
在这里插入图片描述

配置代码

   $config = new \EasySwoole\Pool\Config();
    $redisConfig1 = new \EasySwoole\Redis\Config\RedisConfig(\EasySwoole\EasySwoole\Config::getInstance()->getConf('REDIS'));
    \EasySwoole\Pool\Manager::getInstance()->register(new \App\Pool\RedisPool($config,$redisConfig1),'redis');

使用示例:

<?php
namespace  App\HttpController\Learn;
use EasySwoole\Http\AbstractInterface\Controller;

/**
 * Created by PhpStorm.
 * User: zq2020
 * Date: 20-2-27
 * Time: 下午3:2
 * */
class  Redis extends  Controller{


    public function index()
    {

        $redis=\EasySwoole\Pool\Manager::getInstance()->get('redis')->getObj();
        if(!$res=$redis->get("name")){
            $redis->set("name","zq");
            $redis->expire("name",400);
        }

        $res=$redis->get("name");
        \EasySwoole\Pool\Manager::getInstance()->get('redis')->recycleObj($redis);

        return $this->writeJson(200,$res);

    }


    public function  push(){
        $redis=\EasySwoole\Pool\Manager::getInstance()->get('redis')->getObj();
         $redis->lpush("list",time());
        \EasySwoole\Pool\Manager::getInstance()->get('redis')->recycleObj($redis);
        return $this->writeJson(0,"push list success");
    }

    public function  pop(){
        $redis=\EasySwoole\Pool\Manager::getInstance()->get('redis')->getObj();
        $result=$redis->rpop("list");
        \EasySwoole\Pool\Manager::getInstance()->get('redis')->recycleObj($redis);
        return $this->writeJson(0,$result);
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值