侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

CI框架(CodeIgniter)操作redis的方法详解

Redis  /  管理员 发布于 5年前   352

本文实例讲述了CI框架(CodeIgniter)操作redis的方法。分享给大家供大家参考,具体如下:

1. 在autoload.php 中加入 如下配置行

$autoload['libraries'] = array('redis');

2. 在/application/config 中加入文件 redis.php

文件内容如下:

3. 在 /application/libraries 中加入文件 Redis.php

文件来源:redis库文件包

文件内容:

_ci = get_instance();    $this->_ci->load->config('redis');    // Check for the different styles of configs    if (isset($params['connection_group']))    {      // Specific connection group      $config = $this->_ci->config->item('redis_' . $params['connection_group']);    }    elseif (is_array($this->_ci->config->item('redis_default')))    {      // Default connection group      $config = $this->_ci->config->item('redis_default');    }    else    {      // Original config style      $config = array(        'host' => $this->_ci->config->item('redis_host'),        'port' => $this->_ci->config->item('redis_port'),        'password' => $this->_ci->config->item('redis_password'),      );    }    // Connect to Redis    $this->_connection = @fsockopen($config['host'], $config['port'], $errno, $errstr, 3);    // Display an error message if connection failed    if ( ! $this->_connection)    {      show_error('Could not connect to Redis at ' . $config['host'] . ':' . $config['port']);    }    // Authenticate when needed    $this->_auth($config['password']);  }  /**   * Call   *   * Catches all undefined methods   * @param  string method that was called   * @param  mixed  arguments that were passed   * @return mixed   */  public function __call($method, $arguments)  {    $request = $this->_encode_request($method, $arguments);    return $this->_write_request($request);  }  /**   * Command   *   * Generic command function, just like redis-cli   * @param  string full command as a string   * @return mixed   */  public function command($string)  {    $slices = explode(' ', $string);    $request = $this->_encode_request($slices[0], array_slice($slices, 1));    return $this->_write_request($request);  }  /**   * Auth   *   * Runs the AUTH command when password is set   * @param  string password for the Redis server   * @return void   */  private function _auth($password = NULL)  {    // Authenticate when password is set    if ( ! empty($password))    {      // See if we authenticated successfully      if ($this->command('AUTH ' . $password) !== 'OK')      {        show_error('Could not connect to Redis, invalid password');      }    }  }  /**   * Clear Socket   *   * Empty the socket buffer of theconnection so data does not bleed over   * to the next message.   * @return NULL   */  public function _clear_socket()  {    // Read one character at a time    fflush($this->_connection);    return NULL;  }  /**   * Write request   *   * Write the formatted request to the socket   * @param  string request to be written   * @return mixed   */  private function _write_request($request)  {    if ($this->debug === TRUE)    {      log_message('debug', 'Redis unified request: ' . $request);    }    // How long is the data we are sending?    $value_length = strlen($request);    // If there isn't any data, just return    if ($value_length <= 0) return NULL;    // Handle reply if data is less than or equal to 8192 bytes, just send it over    if ($value_length <= 8192)    {      fwrite($this->_connection, $request);    }    else    {      while ($value_length > 0)      {        // If we have more than 8192, only take what we can handle        if ($value_length > 8192) {          $send_size = 8192;        }        // Send our chunk        fwrite($this->_connection, $request, $send_size);        // How much is left to send?        $value_length = $value_length - $send_size;        // Remove data sent from outgoing data        $request = substr($request, $send_size, $value_length);      }    }    // Read our request into a variable    $return = $this->_read_request();    // Clear the socket so no data remains in the buffer    $this->_clear_socket();    return $return;  }  /**   * Read request   *   * Route each response to the appropriate interpreter   * @return mixed   */  private function _read_request()  {    $type = fgetc($this->_connection);    // Times we will attempt to trash bad data in search of a    // valid type indicator    $response_types = array('+', '-', ':', '$', '*');    $type_error_limit = 50;    $try = 0;    while ( ! in_array($type, $response_types) && $try < $type_error_limit)    {      $type = fgetc($this->_connection);      $try++;    }    if ($this->debug === TRUE)    {      log_message('debug', 'Redis response type: ' . $type);    }    switch ($type)    {      case '+':        return $this->_single_line_reply();        break;      case '-':        return $this->_error_reply();        break;      case ':':        return $this->_integer_reply();        break;      case '$':        return $this->_bulk_reply();        break;      case '*':        return $this->_multi_bulk_reply();        break;      default:        return FALSE;    }  }  /**   * Single line reply   *   * Reads the reply before the EOF   * @return mixed   */  private function _single_line_reply()  {    $value = rtrim(fgets($this->_connection));    $this->_clear_socket();    return $value;  }  /**   * Error reply   *   * Write error to log and return false   * @return bool   */  private function _error_reply()  {    // Extract the error message    $error = substr(rtrim(fgets($this->_connection)), 4);    log_message('error', 'Redis server returned an error: ' . $error);    $this->_clear_socket();    return FALSE;  }  /**   * Integer reply   *   * Returns an integer reply   * @return int   */  private function _integer_reply()  {    return (int) rtrim(fgets($this->_connection));  }  /**   * Bulk reply   *   * Reads to amount of bits to be read and returns value within   * the pointer and the ending delimiter   * @return string   */  private function _bulk_reply()  {    // How long is the data we are reading? Support waiting for data to    // fully return from redis and enter into socket.    $value_length = (int) fgets($this->_connection);    if ($value_length <= 0) return NULL;    $response = '';    // Handle reply if data is less than or equal to 8192 bytes, just read it    if ($value_length <= 8192)    {      $response = fread($this->_connection, $value_length);    }    else    {      $data_left = $value_length;        // If the data left is greater than 0, keep reading        while ($data_left > 0 ) {        // If we have more than 8192, only take what we can handle        if ($data_left > 8192)        {          $read_size = 8192;        }        else        {          $read_size = $data_left;        }        // Read our chunk        $chunk = fread($this->_connection, $read_size);        // Support reading very long responses that don't come through        // in one fread        $chunk_length = strlen($chunk);        while ($chunk_length < $read_size)        {          $keep_reading = $read_size - $chunk_length;          $chunk .= fread($this->_connection, $keep_reading);          $chunk_length = strlen($chunk);        }        $response .= $chunk;        // Re-calculate how much data is left to read        $data_left = $data_left - $read_size;      }    }    // Clear the socket in case anything remains in there    $this->_clear_socket();  return isset($response) ? $response : FALSE;  }  /**   * Multi bulk reply   *   * Reads n bulk replies and return them as an array   * @return array   */  private function _multi_bulk_reply()  {    // Get the amount of values in the response    $response = array();    $total_values = (int) fgets($this->_connection);    // Loop all values and add them to the response array    for ($i = 0; $i < $total_values; $i++)    {      // Remove the new line and carriage return before reading      // another bulk reply      fgets($this->_connection, 2);      // If this is a second or later pass, we also need to get rid      // of the $ indicating a new bulk reply and its length.      if ($i > 0)      {        fgets($this->_connection);        fgets($this->_connection, 2);      }      $response[] = $this->_bulk_reply();    }    // Clear the socket    $this->_clear_socket();    return isset($response) ? $response : FALSE;  }  /**   * Encode request   *   * Encode plain-text request to Redis protocol format   * @link  http://redis.io/topics/protocol   * @param  string request in plain-text   * @param  string additional data (string or array, depending on the request)   * @return string encoded according to Redis protocol   */  private function _encode_request($method, $arguments = array())  {    $request = '$' . strlen($method) . self::CRLF . $method . self::CRLF;    $_args = 1;    // Append all the arguments in the request string    foreach ($arguments as $argument)    {      if (is_array($argument))      {        foreach ($argument as $key => $value)        {          // Prepend the key if we're dealing with a hash          if (!is_int($key))          {            $request .= '$' . strlen($key) . self::CRLF . $key . self::CRLF;            $_args++;          }          $request .= '$' . strlen($value) . self::CRLF . $value . self::CRLF;          $_args++;        }      }      else      {        $request .= '$' . strlen($argument) . self::CRLF . $argument . self::CRLF;        $_args++;      }    }    $request = '*' . $_args . self::CRLF . $request;    return $request;  }  /**   * Info   *   * Overrides the default Redis response, so we can return a nice array   * of the server info instead of a nasty string.   * @return array   */  public function info($section = FALSE)  {    if ($section !== FALSE)    {      $response = $this->command('INFO '. $section);    }    else    {      $response = $this->command('INFO');    }    $data = array();    $lines = explode(self::CRLF, $response);    // Extract the key and value    foreach ($lines as $line)    {      $parts = explode(':', $line);      if (isset($parts[1])) $data[$parts[0]] = $parts[1];    }    return $data;  }  /**   * Debug   *   * Set debug mode   * @param  bool  set the debug mode on or off   * @return void   */  public function debug($bool)  {    $this->debug = (bool) $bool;  }  /**   * Destructor   *   * Kill the connection   * @return void   */  function __destruct()  {    if ($this->_connection) fclose($this->_connection);  }}?>

4. 然后你就可以 在文件中这样使用了

redis->get('mark_'.$gid) === null){ //如果未设置    $this->redis->set('mark_'.$gid, $giftnum); //设置    $this->redis->EXPIRE('mark_'.$gid, 30*60); //设置过期时间 (30 min)  }else{    $giftnum = $this->redis->get('mark_'.$gid); //从缓存中直接读取对应的值  }?>

5. 重点是你所需要的 东东在这里很详细的讲解了

所有要用的函数只需要更改 $redis  ==> $this->redis

php中操作redis库函数功能与用法可参考本站33887.htm

需要注意的是:

(1)你的本地需要安装 redis服务(windows安装)
(2)并开启redis 服务
(3)不管是windows 还是linux 都需要装 php对应版本的 redis扩展

更多关于CodeIgniter相关内容感兴趣的读者可查看本站专题:《codeigniter入门教程》、《CI(CodeIgniter)框架进阶教程》、《php优秀开发框架总结》、《ThinkPHP入门教程》、《ThinkPHP常用方法总结》、《Zend FrameWork框架入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于CodeIgniter框架的PHP程序设计有所帮助。

您可能感兴趣的文章:

  • CI框架中redis缓存相关操作文件示例代码
  • yii框架redis结合php实现秒杀效果(实例代码)
  • PHP的Laravel框架结合MySQL与Redis数据库的使用部署
  • CentOS环境下安装Redis3.0及phpredis扩展测试示例
  • 30个php操作redis常用方法代码例子
  • redis 队列操作的例子(php)
  • php Session存储到Redis的方法
  • php操作redis中的hash和zset类型数据的方法和代码例子
  • PHP实现操作redis的封装类完整实例
  • php框架CodeIgniter使用redis的方法分析


  • 上一条:
    PHP+Redis 消息队列 实现高并发下注册人数统计的实例
    下一条:
    关于 Laravel Redis 多个进程同时取队列问题详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在Redis中能实现的功能、常见应用介绍(0个评论)
    • 2024年Redis面试题之一(0个评论)
    • 在redis缓存常见出错及解决方案(0个评论)
    • 在redis中三种特殊数据类型:地理位置、基数(cardinality)估计、位图(Bitmap)使用场景介绍浅析(2个评论)
    • Redis 删除 key用 del 和 unlink 有啥区别?(1个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-12
    • 2020-03
    • 2020-05
    • 2021-04
    • 2022-03
    • 2022-05
    • 2022-08
    • 2023-02
    • 2023-04
    • 2023-07
    • 2024-01
    • 2024-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客