


This article mainly introduces the method of CI framework (CodeIgniter) operating redis, and analyzes in detail the related configuration and usage skills of CodeIgniter framework for redis database operation in the form of examples. Friends in need can refer to it
The example in this article describes how the CI framework (CodeIgniter) operates redis. Share it with everyone for your reference, the details are as follows:
1. Add the following configuration line to autoload.php
$autoload['libraries'] = array('redis');
2. In / Add the file redis.php
to application/config 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 be left empty when the server does not require AUTH $config['redis_slave']['host'] = ''; $config['redis_slave']['port'] = '6379'; $config['redis_slave']['password'] = ''; ?>
3. Add the file Redis to /application/libraries. php
File source: redis library file package
File content:
<?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. Then you can This is used in
<?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. The key point is that what you need is explained in detail here
All the things you need to use The function only needs to be changed $redis ==> $this->redis
#php to operate the redis library function function and usage, please refer to this site //www.jb51.net/article /33887.htm
It should be noted that:
(1) You need to install the redis service locally (windows installation)
(2) and enable redis Service
(3) Whether it is Windows or Linux, you need to install the redis extension corresponding to PHP
Articles you may be interested in:
php Detailed explanation of using the imagecopymerge() function to create a translucent watermark
The abilities that an intermediate to senior PHP engineer should possess
php Detailed explanation of the code to implement the mysql connection pool effect
The above is the detailed content of Detailed explanation of how CI framework (CodeIgniter) operates redis. For more information, please follow other related articles on the PHP Chinese website!

随着网络技术的发展,PHP已经成为了Web开发的重要工具之一。而其中一款流行的PHP框架——CodeIgniter(以下简称CI)也得到了越来越多的关注和使用。今天,我们就来看看如何使用CI框架。一、安装CI框架首先,我们需要下载CI框架并安装。在CI的官网(https://codeigniter.com/)上下载最新版本的CI框架压缩包。下载完成后,解压缩

CodeIgniter中间件:加速应用程序的响应速度和页面渲染概述:随着网络应用程序的复杂性和交互性不断增长,开发人员需要使用更加高效和可扩展的解决方案来提高应用程序的性能和响应速度。CodeIgniter(CI)是一种基于PHP的轻量级框架,提供了许多有用的功能,其中之一就是中间件。中间件是在请求到达控制器之前或之后执行的一系列任务。这篇文章将介绍如何使用

随着Web应用程序的不断发展,更加快速和高效地开发应用程序变得非常重要。并且,随着RESTfulAPI在Web应用程序中的广泛应用,对于开发人员来说,必须理解如何创建和实现RESTfulAPI。在本文中,我们将讨论如何使用CodeIgniter框架实现MVC模式和RESTfulAPI。MVC模式简介MVC(Model-Vie

PHP是一种流行的编程语言,广泛应用于Web开发。CI(CodeIgniter)框架是PHP中最受欢迎的框架之一,它提供了一整套现成的工具和函数库,以及一些流行的设计模式,让开发人员能够更加高效地开发Web应用程序。本文将介绍使用CI框架开发PHP应用程序的基本步骤和方法。了解CI框架的基本概念和结构在使用CI框架之前,我们需要先了解一些基本的概念和结构。下

CodeIgniter是一个轻量级的PHP框架,采用MVC架构,支持快速开发和简化常见任务。CodeIgniter5是该框架的最新版本,提供了许多新的特性和改进。本文将介绍如何使用CodeIgniter5框架来构建一个简单的Web应用程序。步骤1:安装CodeIgniter5下载和安装CodeIgniter5非常简单,只需要遵循以下步骤:下载最新版本

现今互联网时代,一款深受用户喜爱的网站必须具备简洁明了的前端界面和功能强大的后台管理系统,而PHP框架CodeIgniter则是一款能够让开发者快速搭建后台管理系统的优秀框架。CodeIgniter拥有轻量级、高效率、易扩展等特点,本文将针对初学者,详细说明如何通过该框架快速搭建一个后台管理系统。一、安装配置安装PHPCodeIgniter是一个基于PHP的

近年来,Web开发技术的进步和全球互联网应用的不断扩大,使得PHP技术应用面越来越广泛。作为一种快速开发的技术,其生态系统也在不断发展壮大。其中,CodeIgniter作为PHP开发领域中著名的框架之一,备受众多开发者的欢迎。本篇文章将介绍CodeIgniter框架的相关知识,以此为初学者提供一个入门的指引。一、什么是CodeIgniter框架?CodeIg

随着移动互联网的发展,即时通信变得越来越重要,越来越普及。对于很多企业而言,实时聊天更像是一种通信服务,提供便捷的沟通方式,可以快速有效地解决业务方面的问题。基于此,本文将介绍如何使用PHP框架CodeIgniter开发一个实时聊天应用。了解CodeIgniter框架CodeIgniter是一个轻量级的PHP框架,提供了一系列的简便的工具和库,帮助开发者快速


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools
