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


Posted in PHP onJanuary 25, 2018

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

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

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

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

文件内容如下:

<?php
// Default connection group
$config['redis_default']['host'] = 'localhost';   // IP address or host
$config['redis_default']['port'] = '6379';     // Default Redis port is 6379
$config['redis_default']['password'] = '';     // Can be left empty when the server does not require AUTH
$config['redis_slave']['host'] = '';
$config['redis_slave']['port'] = '6379';
$config['redis_slave']['password'] = '';
?>

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

文件来源:redis库文件包

文件内容:

<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * CodeIgniter Redis
 *
 * A CodeIgniter library to interact with Redis
 *
 * @package     CodeIgniter
 * @category    Libraries
 * @author     Joël Cox
 * @version     v0.4
 * @link      https://github.com/joelcox/codeigniter-redis
 * @link      http://joelcox.nl
 * @license     http://www.opensource.org/licenses/mit-license.html
 */
class CI_Redis {
  /**
   * CI
   *
   * CodeIgniter instance
   * @var   object
   */
  private $_ci;
  /**
   * Connection
   *
   * Socket handle to the Redis server
   * @var   handle
   */
  private $_connection;
  /**
   * Debug
   *
   * Whether we're in debug mode
   * @var   bool
   */
  public $debug = FALSE;
  /**
   * CRLF
   *
   * User to delimiter arguments in the Redis unified request protocol
   * @var   string
   */
  const CRLF = "\r\n";
  /**
   * Constructor
   */
  public function __construct($params = array())
  {
    log_message('debug', 'Redis Class Initialized');
    $this->_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. 然后你就可以 在文件中这样使用了

<?php
  if($this->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库函数功能与用法可参考本站https://3water.com/article/33887.htm

需要注意的是:

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

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

PHP 相关文章推荐
PHP与MySQL开发中页面乱码的产生与解决
Mar 27 PHP
9个PHP开发常用功能函数小结
Jul 15 PHP
iis下php mail函数的sendmail配置方法(官方推荐)
Apr 25 PHP
PHP同时连接多个mysql数据库示例代码
Mar 17 PHP
php递归遍历多维数组的方法
Apr 18 PHP
ThinkPHP文件缓存类代码分享
Apr 22 PHP
通过PHP自带的服务器来查看正则匹配结果的方法
Dec 24 PHP
Yii2中SqlDataProvider用法示例
Sep 22 PHP
PHP上传Excel文件导入数据到MySQL数据库示例
Oct 25 PHP
thinkPHP中钩子的两种配置调用方法详解
Nov 11 PHP
php中get_magic_quotes_gpc()函数说明
Feb 06 PHP
PHP中函数gzuncompress无法使用的解决方法
Mar 02 PHP
PHP开发之用微信远程遥控服务器
Jan 25 #PHP
php实现统计二进制中1的个数算法示例
Jan 23 #PHP
基于php中echo用逗号和用点号的区别详解
Jan 23 #PHP
php数据结构之顺序链表与链式线性表示例
Jan 22 #PHP
通过源码解析Laravel的依赖注入
Jan 22 #PHP
phpstorm 正则匹配删除空行、注释行(替换注释行为空行)
Jan 21 #PHP
php语言注释,单行注释和多行注释
Jan 21 #PHP
You might like
destoon二次开发常用数据库操作
2014/06/21 PHP
php实现遍历文件夹的方法汇总
2017/03/02 PHP
PHP 自动加载类原理与用法实例分析
2020/04/14 PHP
不错的新闻标题颜色效果
2006/12/10 Javascript
跟着JQuery API学Jquery 之三 筛选
2010/04/09 Javascript
获取div编辑框,textarea,input text的光标位置 兼容IE,FF和Chrome的方法介绍
2012/11/08 Javascript
javascript控制swfObject应用介绍
2012/11/29 Javascript
js改变鼠标的形状和样式的方法
2014/03/31 Javascript
jquery使用hide方法隐藏指定id的元素
2015/03/30 Javascript
jQuery Easyui学习之datagrid 动态添加、移除editor
2016/01/27 Javascript
浅谈Angular.js中使用$watch监听模型变化
2017/01/10 Javascript
如何正确理解javascript的模块化
2017/03/02 Javascript
vue实现按需加载组件及异步组件功能
2019/05/27 Javascript
详解JavaScript 事件流
2020/09/02 Javascript
vue中使用vue-pdf的方法详解
2020/09/05 Javascript
vue解决跨域问题(推荐)
2020/11/10 Javascript
在Python的Django框架中simple-todo工具的简单使用
2015/05/30 Python
Python实现删除当前目录下除当前脚本以外的文件和文件夹实例
2015/07/27 Python
python使用json序列化datetime类型实例解析
2018/02/11 Python
python实现微信发送邮件关闭电脑功能
2018/02/22 Python
python让列表倒序输出的实例
2018/06/25 Python
python3解析库lxml的安装与基本使用
2018/06/27 Python
为何人工智能(AI)首选Python?读完这篇文章你就知道了(推荐)
2019/04/06 Python
python3.6生成器yield用法实例分析
2019/08/23 Python
Python的缺点和劣势分析
2019/11/19 Python
Python使用多进程运行含有任意个参数的函数
2020/05/02 Python
Python configparser模块应用过程解析
2020/08/14 Python
Spongelle官网:美国的创意护肤洗护品牌
2019/05/15 全球购物
最新的大学生找工作自我评价
2013/09/29 职场文书
历史学专业大学生找工作的自我评价
2013/10/16 职场文书
银行实习生的自我评价
2013/12/09 职场文书
会计自荐信范文
2014/03/09 职场文书
诚信考试承诺书
2014/03/27 职场文书
村主任“四风”问题个人对照检查材料思想汇报
2014/10/02 职场文书
2015年维修电工工作总结
2015/04/25 职场文书
Vue+Flask实现图片传输功能
2022/04/01 Vue.js