本文实例讲述了CI框架中redis缓存相关操作文件,

作者:美狮美高梅官方网站

本文实例讲述了CI框架中redis缓存相关操作文件。分享给大家供大家参考,具体如下:

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

redis缓存类文件位置:

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

    $autoload['libraries'] = array;

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

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

'cisystemlibrariesCachedriversCache_redis.php'

文件来源:redis库文件包

 * @link */class CI_Cache_redis extends CI_Driver{ /** * Default config * * @static * @var array */ protected static $_default_config = array( /* 'socket_type' => 'tcp', 'host' => '127.0.0.1', 'password' => NULL, 'port' => 6379, 'timeout' => 0 */ ); /** * Redis connection * * @var Redis */ protected $_redis; /** * Get cache * * @param string like *$key* * @return array */ public function keys { return $this->_redis->keys; } /** * Get cache * * @param string Cache ID * @return mixed */ public function get { return $this->_redis->get; } /** * mGet cache * * @param array Cache ID Array * @return mixed */ public function mget { return $this->_redis->mget; } /** * Save cache * * @param string $id Cache ID * @param mixed $data Data to save * @param int $ttl Time to live in seconds * @param bool $raw Whether to store the raw value  * @return bool TRUE on success, FALSE on failure */ public function save($id, $data, $ttl = 60, $raw = FALSE) { return  ? $this->_redis->setex : $this->_redis->set; } /** * Delete from cache * * @param string Cache key * @return bool */ public function delete { return ($this->_redis->delete; } /** * hIncrBy a raw value * * @param string $id Cache ID * @param string $field Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hincrby($key, $field, $value = 1) { return $this->_redis->hIncrBy; } /** * hIncrByFloat a raw value * * @param string $id Cache ID * @param string $field Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hincrbyfloat($key, $field, $value = 1) { return $this->_redis->hIncrByFloat; } /** * lpush a raw value * * @param string $key Cache ID * @param string $value value * @return mixed New value on success or FALSE on failure */ public function lpush { return $this->_redis->lPush; } /** * rpush a raw value * * @param string $key Cache ID * @param string $value value * @return mixed New value on success or FALSE on failure */ public function rpush { return $this->_redis->rPush; } /** * rpop a raw value * * @param string $key Cache ID * @param string $value value * @return mixed New value on success or FALSE on failure */ public function rpop { return $this->_redis->rPop; } /** * brpop a raw value * * @param string $key Cache ID * @param string $ontime 阻塞等待时间 * @return mixed New value on success or FALSE on failure */ public function brpop { return $this->_redis->brPop; } /** * lLen a raw value * * @param string $key Cache ID * @return mixed Value on success or FALSE on failure */ public function llen { return $this->_redis->lLen; } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function increment { return $this->_redis->exists ? $this->_redis->incr : FALSE; } /** * incrby a raw value * * @param string $key Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function incrby { return $this->_redis->incrby; } /** * set a value expire time * * @param string $key Cache ID * @param int $seconds expire seconds * @return mixed New value on success or FALSE on failure */ public function expire { return $this->_redis->expire; } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hset { return $this->_redis->hset; } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hget { return $this->_redis->hget; } /** * Increment a raw value * * @param string $id Cache ID * @return mixed New value on success or FALSE on failure */ public function hkeys { return $this->_redis->hkeys; } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hgetall { return $this->_redis->hgetall; } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hmget { return $this->_redis->hmget; } /** * del a key value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hdel { return $this->_redis->hdel; } /** * del a key value * * @param string $id Cache ID * @return mixed New value on success or FALSE on failure */ public function hvals { return $this->_redis->hvals; } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hmset { return $this->_redis->hmset; } /** * Decrement a raw value * * @param string $id Cache ID * @param int $offset Step/value to reduce by * @return mixed New value on success or FALSE on failure */ public function decrement { return $this->_redis->exists ? $this->_redis->decr : FALSE; } /** * Clean cache * * @return bool * @see Redis::flushDB() */ public function clean() { return $this->_redis->flushDB(); } /** * Get cache driver info * * @param string Not supported in Redis. * Only included in order to offer a * consistent cache API. * @return array * @see Redis::info() */ public function cache_info { return $this->_redis->info(); } /** * Get cache metadata * * @param string Cache key * @return array */ public function get_metadata { $value = $this->get { return array + $this->_redis->ttl, 'data' => $value ); } return FALSE; } /** * Check if Redis driver is supported * * @return bool */ public function is_supported() { if (extension_loaded { return $this->_setup_redis(); } else { log_message('debug', 'The Redis extension must be loaded to use Redis cache.'); return FALSE; } } /** * Setup Redis config and connection * * Loads Redis config file if present. Will halt execution * if a Redis connection can't be established. * * @return bool * @see Redis::connect() */ protected function _setup_redis; $CI =& get_instance(); if ($CI->config->load { $config += $CI->config->item; } $config = array_merge(self::$_default_config, $config); $config = !empty?$config['redis']:$config; $this->_redis = new Redis(); try { if ($config['socket_type'] === 'unix') { $success = $this->_redis->connect; } else // tcp socket { $success = $this->_redis->connect($config['host'], $config['port'], $config['timeout']); } if  { log_message('debug', 'Cache: Redis connection refused. Check the config.'); return FALSE; } } catch  { log_message('debug', 'Cache: Redis connection refused '); return FALSE; } if (isset { $this->_redis->auth; } return TRUE; } /** * Class destructor * * Closes the connection to Redis if present. * * @return void */ public function __destruct() { if  { $this->_redis->close(); } }}/* End of file Cache_redis.php *//* Location: ./system/libraries/Cache/drivers/Cache_redis.php */
_ci = get_instance(); $this->_ci->load->config; // 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 { // Default connection group $config = $this->_ci->config->item; } else { // Original config style $config = array( 'host' => $this->_ci->config->item, 'port' => $this->_ci->config->item, 'password' => $this->_ci->config->item; } // 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; } /** * Call * * Catches all undefined methods * @param string method that was called * @param mixed arguments that were passed * @return mixed */ public function __call { $request = $this->_encode_request; return $this->_write_request; } /** * Command * * Generic command function, just like redis-cli * @param string full command as a string * @return mixed */ public function command { $slices = explode; $request = $this->_encode_request($slices[0], array_slice; return $this->_write_request; } /** * Auth * * Runs the AUTH command when password is set * @param string password for the Redis server * @return void */ private function _auth { // Authenticate when password is set if  { // See if we authenticated successfully if ($this->command !== '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; return NULL; } /** * Write request * * Write the formatted request to the socket * @param string request to be written * @return mixed */ private function _write_request { if ($this->debug === TRUE) { log_message('debug', 'Redis unified request: ' . $request); } // How long is the data we are sending? $value_length = strlen; // If there isn't any data, just return if  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  { // If we have more than 8192, only take what we can handle if  { $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; // 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; $try++; } if ($this->debug === TRUE) { log_message('debug', 'Redis response type: ' . $type); } switch  { 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->_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, 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 rtrim(fgets; } /** * 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 =  fgets; if  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  { // If we have more than 8192, only take what we can handle if  { $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; while ($chunk_length < $read_size) { $keep_reading = $read_size - $chunk_length; $chunk .= fread($this->_connection, $keep_reading); $chunk_length = strlen; } $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 : 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 =  fgets; // 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  { fgets; fgets($this->_connection, 2); } $response[] = $this->_bulk_reply(); } // Clear the socket $this->_clear_socket(); return isset ? $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 . self::CRLF . $method . self::CRLF; $_args = 1; // Append all the arguments in the request string foreach ($arguments as $argument) { if  { foreach ($argument as $key => $value) { // Prepend the key if we're dealing with a hash if  { $request .= '$' . strlen . self::CRLF . $key . self::CRLF; $_args++; } $request .= '$' . strlen . self::CRLF . $value . self::CRLF; $_args++; } } else { $request .= '$' . strlen . 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 { if  { $response = $this->command; } else { $response = $this->command; } $data = array(); $lines = explode(self::CRLF, $response); // Extract the key and value foreach  { $parts = explode; if  $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 { $this->debug =  $bool; } /** * Destructor * * Kill the connection * @return void */ function __destruct() { if  fclose; }}?>

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

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

    redis->get === null){ //如果未设置 $this->redis->set('mark新美高梅网站,_'.$gid, $giftnum); //设置 $this->redis->EXPIRE; //设置过期时间 }else{ $giftnum = $this->redis->get; //从缓存中直接读取对应的值 }?>

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

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

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

本文由美狮美高梅官方网站发布,转载请注明来源

关键词: