CI Framework (CodeIgniter) methods for operating Redis

Source: Internet
Author: User
Tags autoload fread rtrim codeigniter redis server
This article mainly introduces the CI framework (codeigniter) operation of Redis method, analyzes the CodeIgniter framework for Redis database operation of the relevant configuration and use of skills, the need for friends can refer to the following

This example describes the CI framework (CodeIgniter) approach to Redis operations. Share to everyone for your reference, as follows:

1. Add the following configuration line in the autoload.php

$autoload [' libraries '] = Array (' Redis ');

2. Add a file to the/application/config redis.php

The contents of the file are as follows:

<?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 is left empty when the server does not require auth$config[' redis_slave ' [' host '] = '; $config [' Redis_slave '] [' Port '] = ' 6379 '; $config [' Redis_slave '] [' password '] = ';? >

3. Add a file to the/application/libraries redis.php

File Source: Redis Library file Package

File contents:

<?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.OPENSOURC e.org/licenses/mit-license.html */class Ci_redis {/** * CI * * CodeIgniter Instance * @var Object */privat  e $_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 Initializ    Ed ');    $this->_ci = Get_instance ();$this->_ci->load->config (' Redis '); Check for the different styles of configs if (Isset ($params [' Connection_group '])) {//Specific connection G    Roup $config = $this->_ci->config->item (' Redis_ ' $params [' connection_group ']); } elseif (Is_array ($this->_ci->config->item (' Redis_default '))) {//default connection group $con    Fig = $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-&    Gt;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 and was called * @param mixed Argumen TS 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 was set * @param string password for the Redis server * @r eturn void */Private Function _auth ($password = NULL) {//Authenticate when password is Set if (! Empty ($password)) {//See if we authenticated successfully if ($this->command (' AUTH '. $p      Assword) (!== ' OK ') {show_error (' Could not connect to Redis, invalid password '); }}}/** * Clear Socket * * Empty the socket buffer of theconnection so data does does bleed over * to the NE   XT 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 * @r Eturn Mixed */Private Function _write_request ($request) {if ($this->debug = = = TRUE) {log_message (' Deb UG ', ' Redis Unified request: '.    $request);    }//How long was 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 orEqual to 8192 bytes, just send it over if ($value _length <= 8192) {fwrite ($this->_connection, $request); } else {while ($value _length > 0) {//If we had more than 8192, and only take the what we can Han        Dle if ($value _length > 8192) {$send _size = 8192;        }//Send our chunk fwrite ($this->_connection, $request, $send _size);        How much are 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 functio    n _read_request () {$type = fgetc ($this->_connection); times weWould 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->_conn      ection);    $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_li Ne_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 () {RE  Turn (int) RTrim (fgets ($this->_connection)); }/** * Bulk reply * * Reads to amount of bits to be read and returns value within * the pointer and the ending D Elimiter * @return String */Private Function _bulk_reply () {//How long was 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) {$resp    Onse = Fread ($this->_connection, $value _length);        } else {$data _left = $value _length; If the data is greater than 0, keep reading while ($data _left > 0) {//If we had more than 819        2, 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 this 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 was 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 funct    Ion _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 was 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/pro Tocol * @param string request in Plain-text * @param string Additional data (string or array, depending on the Reque ST) * @return string encoded according to REDIS protocol */Private function _encode_request ($method, $arguments = AR    Ray ()) {$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-&gt    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 debugmode on or off * @return void */Public Function debug ($bool) {$this->debug = (bool) $bool; }/** * destructor * Kill the connection * @return void */function __destruct () {if ($this->_connec  tion) fclose ($this->_connection); }}?>

4. Then you can use it in the file

<?php if  ($this->redis->get (' Mark_ '. $gid) = = = NULL) {//if    $this->redis->set is not set (' Mark_ '. $gid , $giftnum); Set    $this->redis->expire (' Mark_ '. $gid, 30*60);//Set Expiration Time (min)  }else{    $giftnum = $this Redis->get (' Mark_ '. $gid); Read the corresponding value directly from the cache  }?>

5. The emphasis is on what you need to explain it in detail here.

All functions to be used only need to be changed

$redis  ==> $this->redis

It is important to note that:

(1) Your local need to install the Redis service (Windows installation)
(2) and open Redis service
(3) Both Windows and Linux require a PHP version of the Redis extension

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.