ホームページ バックエンド開発 PHPチュートリアル CIフレームワーク(CodeIgniter)のredisの動作を詳しく解説

CIフレームワーク(CodeIgniter)のredisの動作を詳しく解説

Jun 29, 2018 pm 05:31 PM
CIフレームワーク codeigniter redis

この記事では、主に Redis を操作するための CI フレームワーク (CodeIgniter) の方法を紹介し、サンプルの形で Redis データベース操作のための CodeIgniter フレームワークの関連構成と使用スキルを詳細に分析します。

## この記事の例では、CI フレームワーク (CodeIgniter) が Redis を操作する方法について説明します。参考のために全員と共有してください。詳細は次のとおりです。

1. 次の設定行を autoload.php に追加します。

$autoload['libraries'] = array('redis');
ログイン後にコピー

2. 次のように、redis.php

ファイルを application/config に追加します。

<?php
// Default connection group
$config[&#39;redis_default&#39;][&#39;host&#39;] = &#39;localhost&#39;;   // IP address or host
$config[&#39;redis_default&#39;][&#39;port&#39;] = &#39;6379&#39;;     // Default Redis port is 6379
$config[&#39;redis_default&#39;][&#39;password&#39;] = &#39;&#39;;     // Can be left empty when the server does not require AUTH
$config[&#39;redis_slave&#39;][&#39;host&#39;] = &#39;&#39;;
$config[&#39;redis_slave&#39;][&#39;port&#39;] = &#39;6379&#39;;
$config[&#39;redis_slave&#39;][&#39;password&#39;] = &#39;&#39;;
?>
ログイン後にコピー

3 ファイル Redis を / に追加します。 application/libraries.php

ファイル ソース: redis ライブラリ ファイル パッケージ

ファイルの内容:

<?php defined(&#39;BASEPATH&#39;) OR exit(&#39;No direct script access allowed&#39;);
/**
 * 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&#39;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(&#39;debug&#39;, &#39;Redis Class Initialized&#39;);
    $this->_ci = get_instance();
    $this->_ci->load->config(&#39;redis&#39;);
    // Check for the different styles of configs
    if (isset($params[&#39;connection_group&#39;]))
    {
      // Specific connection group
      $config = $this->_ci->config->item(&#39;redis_&#39; . $params[&#39;connection_group&#39;]);
    }
    elseif (is_array($this->_ci->config->item(&#39;redis_default&#39;)))
    {
      // Default connection group
      $config = $this->_ci->config->item(&#39;redis_default&#39;);
    }
    else
    {
      // Original config style
      $config = array(
        &#39;host&#39; => $this->_ci->config->item(&#39;redis_host&#39;),
        &#39;port&#39; => $this->_ci->config->item(&#39;redis_port&#39;),
        &#39;password&#39; => $this->_ci->config->item(&#39;redis_password&#39;),
      );
    }
    // Connect to Redis
    $this->_connection = @fsockopen($config[&#39;host&#39;], $config[&#39;port&#39;], $errno, $errstr, 3);
    // Display an error message if connection failed
    if ( ! $this->_connection)
    {
      show_error(&#39;Could not connect to Redis at &#39; . $config[&#39;host&#39;] . &#39;:&#39; . $config[&#39;port&#39;]);
    }
    // Authenticate when needed
    $this->_auth($config[&#39;password&#39;]);
  }
  /**
   * 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(&#39; &#39;, $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(&#39;AUTH &#39; . $password) !== &#39;OK&#39;)
      {
        show_error(&#39;Could not connect to Redis, invalid password&#39;);
      }
    }
  }
  /**
   * 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(&#39;debug&#39;, &#39;Redis unified request: &#39; . $request);
    }
    // How long is the data we are sending?
    $value_length = strlen($request);
    // If there isn&#39;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(&#39;+&#39;, &#39;-&#39;, &#39;:&#39;, &#39;$&#39;, &#39;*&#39;);
    $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(&#39;debug&#39;, &#39;Redis response type: &#39; . $type);
    }
    switch ($type)
    {
      case &#39;+&#39;:
        return $this->_single_line_reply();
        break;
      case &#39;-&#39;:
        return $this->_error_reply();
        break;
      case &#39;:&#39;:
        return $this->_integer_reply();
        break;
      case &#39;$&#39;:
        return $this->_bulk_reply();
        break;
      case &#39;*&#39;:
        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(&#39;error&#39;, &#39;Redis server returned an error: &#39; . $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 = &#39;&#39;;
    // 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&#39;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 = &#39;$&#39; . 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&#39;re dealing with a hash
          if (!is_int($key))
          {
            $request .= &#39;$&#39; . strlen($key) . self::CRLF . $key . self::CRLF;
            $_args++;
          }
          $request .= &#39;$&#39; . strlen($value) . self::CRLF . $value . self::CRLF;
          $_args++;
        }
      }
      else
      {
        $request .= &#39;$&#39; . strlen($argument) . self::CRLF . $argument . self::CRLF;
        $_args++;
      }
    }
    $request = &#39;*&#39; . $_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(&#39;INFO &#39;. $section);
    }
    else
    {
      $response = $this->command(&#39;INFO&#39;);
    }
    $data = array();
    $lines = explode(self::CRLF, $response);
    // Extract the key and value
    foreach ($lines as $line)
    {
      $parts = explode(&#39;:&#39;, $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(&#39;mark_&#39;.$gid) === null){ //如果未设置
    $this->redis->set(&#39;mark_&#39;.$gid, $giftnum); //设置
    $this->redis->EXPIRE(&#39;mark_&#39;.$gid, 30*60); //设置过期时间 (30 min)
  }else{
    $giftnum = $this->redis->get(&#39;mark_&#39;.$gid); //从缓存中直接读取对应的值
  }
?>
ログイン後にコピー

5 で使用されます。重要な点は、ここで必要なものが詳しく説明されているということです。

必要なものがすべて揃っているということです。使用するには関数を変更するだけです

$redis ==> $this->redis

#php を操作するには、redis ライブラリ関数の機能と使用方法を参照してください。 //www.jb51.net/article /33887.htm

次の点に注意してください:

(1) Redis サービスをローカル (Windows) にインストールする必要があります。インストール)

(2) そして redis サービスを有効にします
(3) Windows か Linux かに関係なく、PHP

記事に対応する Redis 拡張機能をインストールする必要があります。興味のあるもの:

php imagecopymerge() 関数を使用して半透明のウォーターマークを作成する方法の詳細な説明

中級者から上級者が必要とする能力PHP エンジニアは次のことを理解する必要があります

php mysql 接続プール効果を実装するコードの詳細な説明

以上がCIフレームワーク(CodeIgniter)のredisの動作を詳しく解説の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Redisクラスターモードの構築方法 Redisクラスターモードの構築方法 Apr 10, 2025 pm 10:15 PM

Redisクラスターモードは、シャードを介してRedisインスタンスを複数のサーバーに展開し、スケーラビリティと可用性を向上させます。構造の手順は次のとおりです。異なるポートで奇妙なRedisインスタンスを作成します。 3つのセンチネルインスタンスを作成し、Redisインスタンスを監視し、フェールオーバーを監視します。 Sentinel構成ファイルを構成し、Redisインスタンス情報とフェールオーバー設定の監視を追加します。 Redisインスタンス構成ファイルを構成し、クラスターモードを有効にし、クラスター情報ファイルパスを指定します。各Redisインスタンスの情報を含むnodes.confファイルを作成します。クラスターを起動し、CREATEコマンドを実行してクラスターを作成し、レプリカの数を指定します。クラスターにログインしてクラスター情報コマンドを実行して、クラスターステータスを確認します。作る

基礎となるRedisを実装する方法 基礎となるRedisを実装する方法 Apr 10, 2025 pm 07:21 PM

Redisはハッシュテーブルを使用してデータを保存し、文字列、リスト、ハッシュテーブル、コレクション、注文コレクションなどのデータ構造をサポートします。 Redisは、スナップショット(RDB)を介してデータを維持し、書き込み専用(AOF)メカニズムを追加します。 Redisは、マスタースレーブレプリケーションを使用して、データの可用性を向上させます。 Redisは、シングルスレッドイベントループを使用して接続とコマンドを処理して、データの原子性と一貫性を確保します。 Redisは、キーの有効期限を設定し、怠zyな削除メカニズムを使用して有効期限キーを削除します。

Redisのすべてのキーを表示する方法 Redisのすべてのキーを表示する方法 Apr 10, 2025 pm 07:15 PM

Redisのすべてのキーを表示するには、3つの方法があります。キーコマンドを使用して、指定されたパターンに一致するすべてのキーを返します。スキャンコマンドを使用してキーを繰り返し、キーのセットを返します。情報コマンドを使用して、キーの総数を取得します。

Redisのバージョン番号を表示する方法 Redisのバージョン番号を表示する方法 Apr 10, 2025 pm 05:57 PM

Redisバージョン番号を表示するには、次の3つの方法を使用できます。(1)情報コマンドを入力し、(2) - versionオプションでサーバーを起動し、(3)構成ファイルを表示します。

Redis-Serverが見つからない場合はどうすればよいですか Redis-Serverが見つからない場合はどうすればよいですか Apr 10, 2025 pm 06:54 PM

Redis-Serverが見つからない問題を解決するための手順:インストールを確認して、Redisが正しくインストールされていることを確認します。環境変数Redis_hostとredis_portを設定します。 Redis Server Redis-Serverを起動します。サーバーがRedis-Cli pingを実行しているかどうかを確認します。

Redis Zsetの使用方法 Redis Zsetの使用方法 Apr 10, 2025 pm 07:27 PM

Redis Orderedセット(ZSET)は、並べ替えられた要素を保存し、関連するスコアでソートするために使用されます。 zsetを使用する手順には次のものがあります。1。zsetを作成します。 2。メンバーを追加します。 3.メンバースコアを取得します。 4。ランキングを取得します。 5.ランキング範囲のメンバーを取得します。 6.メンバーを削除します。 7.要素の数を取得します。 8。スコア範囲のメンバーの数を取得します。

Redisのソースコードを読み取る方法 Redisのソースコードを読み取る方法 Apr 10, 2025 pm 08:27 PM

Redisソースコードを理解する最良の方法は、段階的に進むことです。Redisの基本に精通してください。開始点として特定のモジュールまたは機能を選択します。モジュールまたは機能のエントリポイントから始めて、行ごとにコードを表示します。関数コールチェーンを介してコードを表示します。 Redisが使用する基礎となるデータ構造に精通してください。 Redisが使用するアルゴリズムを特定します。

Redisコマンドの使用方法 Redisコマンドの使用方法 Apr 10, 2025 pm 08:45 PM

Redis指令を使用するには、次の手順が必要です。Redisクライアントを開きます。コマンド(動詞キー値)を入力します。必要なパラメーターを提供します(指示ごとに異なります)。 Enterを押してコマンドを実行します。 Redisは、操作の結果を示す応答を返します(通常はOKまたは-ERR)。

See all articles