codeigniter的Redis使用

2024-04-02 12:38
文章标签 使用 redis codeigniter

本文主要是介绍codeigniter的Redis使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Redis的配置和简单使用1:

1.system/config/redis.php:

<?php
$config['redis_host']     = '127.0.0.1';
$config['redis_port']     = '6379';
$config['redis_isopen']   = true;
  1. ./application/config/config.php:
require_once(BASEPATH . "config/redis.php");

3 . ./application/libraries/RedisService.php:

<?php
class RedisService{public $CI;public $redis;public function __construct(){$this->CI = & get_instance();$this->CI->load->driver('cache', array('adapter' => 'redis'));$this->redis = $this->CI->cache->get_redis();$this->cache = $this->CI->cache;}
}

4…/system/libraries/Cache/Cache.php:

protected $valid_drivers    = array(
protected $valid_drivers = array('apc','dummy','file','memcached','redis','wincache');
修改:
/*** Reference to the driver** @var mixed*///protected $_adapter = 'dummy';protected $_adapter = 'redis'; // change by wuyongyu/*** Fallback driver** @var string*///protected $_backup_driver = 'dummy';protected $_backup_driver = 'redis'; // change by wuyongyu

//添加:

public function get_redis(){if($this->_adapter == 'redis'){return $this->{$this->_adapter}->get_redis();}return false;
}

5 . ./system/libraries/Cache/drivers/Cache_redis.php


<?php
/*** CodeIgniter** An open source application development framework for PHP** This content is released under the MIT License (MIT)** Copyright (c) 2014 - 2015, British Columbia Institute of Technology** Permission is hereby granted, free of charge, to any person obtaining a copy* of this software and associated documentation files (the "Software"), to deal* in the Software without restriction, including without limitation the rights* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell* copies of the Software, and to permit persons to whom the Software is* furnished to do so, subject to the following conditions:** The above copyright notice and this permission notice shall be included in* all copies or substantial portions of the Software.** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN* THE SOFTWARE.** @package	CodeIgniter* @author	EllisLab Dev Team* @copyright	Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)* @copyright	Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)* @license	http://opensource.org/licenses/MIT	MIT License* @link	http://codeigniter.com* @since	Version 3.0.0* @filesource*/
defined('BASEPATH') OR exit('No direct script access allowed');/*** CodeIgniter Redis Caching Class** @package	   CodeIgniter* @subpackage Libraries* @category   Core* @author	   Anton Lindqvist <anton@qvister.se>* @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' => 'adasadsa', // NULL change by wuyongyu'port' => 6379,'timeout' => 0);/*** Redis connection** @var	Redis*/protected $_redis;/*** An internal cache for storing keys of serialized values.** @var	array*/protected $_serialized = array();// ------------------------------------------------------------------------/*** Get cache** @param	string	Cache ID* @return	mixed*/public function get($key){$value = $this->_redis->get($key);if ($value !== FALSE && isset($this->_serialized[$key])){return unserialize($value);}return $value;}// ------------------------------------------------------------------------/*** 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 (unused)* @return	bool	TRUE on success, FALSE on failure*/public function save($id, $data, $ttl = 60, $raw = FALSE){if (is_array($data) OR is_object($data)){if ( ! $this->_redis->sIsMember('_ci_redis_serialized', $id) && ! $this->_redis->sAdd('_ci_redis_serialized', $id)){return FALSE;}isset($this->_serialized[$id]) OR $this->_serialized[$id] = TRUE;$data = serialize($data);}elseif (isset($this->_serialized[$id])){$this->_serialized[$id] = NULL;$this->_redis->sRemove('_ci_redis_serialized', $id);}return ($ttl)? $this->_redis->setex($id, $ttl, $data): $this->_redis->set($id, $data);}// ------------------------------------------------------------------------/*** Delete from cache** @param	string	Cache key* @return	bool*/public function delete($key){if ($this->_redis->delete($key) !== 1){return FALSE;}if (isset($this->_serialized[$key])){$this->_serialized[$key] = NULL;$this->_redis->sRemove('_ci_redis_serialized', $key);}return TRUE;}// ------------------------------------------------------------------------/*** 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($id, $offset = 1){return $this->_redis->incr($id, $offset);}// ------------------------------------------------------------------------/*** 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($id, $offset = 1){return $this->_redis->decr($id, $offset);}// ------------------------------------------------------------------------/*** 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($type = NULL){return $this->_redis->info();}// ------------------------------------------------------------------------/*** Get cache metadata** @param	string	Cache key* @return	array*/public function get_metadata($key){$value = $this->get($key);if ($value){return array('expire' => time() + $this->_redis->ttl($key),'data' => $value);}return FALSE;}// ------------------------------------------------------------------------/*** Check if Redis driver is supported** @return	bool*/public function is_supported(){if ( ! extension_loaded('redis')){log_message('debug', 'The Redis extension must be loaded to use Redis cache.');return FALSE;}return $this->_setup_redis();}// ------------------------------------------------------------------------/*** 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(){$config = array();$CI =& get_instance();if ($CI->config->load('redis', TRUE, TRUE)){$config += $CI->config->item('redis');}$config = array_merge(self::$_default_config, $config);$this->_redis = new Redis();//log_message('error',$config);try{if ($config['socket_type'] === 'unix'){$success = $this->_redis->connect($config['socket']);}else // tcp socket{$success = $this->_redis->connect($config['host'], $config['port'], $config['timeout']);}if ( ! $success){log_message('debug', 'Cache: Redis connection refused. Check the config.');return FALSE;}}catch (RedisException $e){log_message('debug', 'Cache: Redis connection refused ('.$e->getMessage().')');return FALSE;}if (isset($config['password'])){$this->_redis->auth($config['password']);}// Initialize the index of serialized values.$serialized = $this->_redis->sMembers('_ci_redis_serialized');if ( ! empty($serialized)){$this->_serialized = array_flip($serialized);}return TRUE;}// ------------------------------------------------------------------------/*** Class destructor** Closes the connection to Redis if present.** @return	void*/public function __destruct(){if ($this->_redis){$this->_redis->close();}}public function get_redis(){return $this->_redis;}}

6 . 控制器中就可以使用啦:

//初始化:
$this->load->library('RedisService');
$this->redis = new RedisService;//使用:
$this->redis->redis->set('name', 'chenjian');
$this->redis->redis->get('name');

二. Redis 实际使用
使用redis 对数据库请求进行缓存.
~示例~:

1 . 控制器中:****

$this->load->model("user"); //初始化
$this->load->library( 'cache_mgr' ); //引用cache_mgr库文件
/*
get_cache有四个参数:get_cache(key, model里面的方法, 参数数组, 缓存的时长),且get_cache方法不仅仅可以取缓存,如果没有缓存就执行model里面的方法,并且缓存。
*/$this->cache_mgr = new CacheMgr();$data = $this->cache_mgr->get_cache($key, array($this->user, 'get_user'), array('age' => $age), 60 * 60);
}

application/libraries/CacheMgr里面的库文件:

<?php
class CacheMgr{protected static $redis;protected $host;protected $port;protected $pwd;protected $is_open;private $_config = array();public function __construct(){$this->_config = get_config();$this->host    = $this->_config['redis_host'];$this->port    = $this->_config['redis_port'];$this->is_open = $this->_config['redis_isopen'];$this->pwd     = $this->_config['redis_pwd'];if (! $this->is_open) {self::$redis = null;} elseif (! self::$redis)$this->connect ();}/**** @return cache_mgr*/static function get_instance(){$ci = get_instance ();$var = __CLASS__;return $ci->$var;}/*** 返回当前rediscache服务器是否有效** @return boolean*/public function is_connected(){return self::$redis ? true : false;}/*** 连接rediscache*/private function connect(){self::$redis = new Redis();if (! @self::$redis->connect ( $this->host, $this->port )) {self::$redis = null;// echo "not redis";} else {self::$redis->auth($this->pwd);}}/*** 前端代码读写缓存。所有前端代码只能用这个方法来写缓存** @param string $key 键值,可为数组array(group值,键值),group值可以用做批量删除* @param callback $function* @param array $params* @param int $expire* @return mixed*/public function get_cache($key, $function, $params = array(), $expire = 0){// 如果缓存没有开if (! self::$redis) {return call_user_func_array ( $function, $params );}$rs = $this->get ( $key );if (! $rs) {$rs = call_user_func_array ( $function, $params );if (! $rs) $expire = 5 * 60;$this->save( $key, $rs, $expire );}return $rs;}/*** 要清除的缓存** @param string $key*/public function clear($key){return self::$redis ? self::$redis->delete ( $key ) : false;}/*** Get cache** @param   string  $key    Cache ID* @return  mixed*/public function get($key){$data = self::$redis->hMGet($key, array('__ci_value'));if ( ! isset($data['__ci_value']) OR $data['__ci_value'] === FALSE){return FALSE;}return unserialize($data['__ci_value']);}/*** 生成缓存,通常用于后台** @param string $key* @param string $value* @param int $ttl 过期秒数,为0时永不过期* @return bool*/public function save($key, $value, $ttl = 60, $raw = FALSE){if ( ! self::$redis->hMSet($key, array('__ci_value' => serialize ($value)))){return FALSE;}elseif ($ttl){self::$redis->expireAt($key, time() + $ttl);}return TRUE;}/*** 加法,只能对数值型缓存使用,对 key 的值做++操作,并返回** @param string $key* @param int $value*/public function increment($key, $offset = 1){return self::$redis ? self::$redis->hIncrBy($key, 'data', $offset) : false;}/*** 减法,只能对数值型缓存使用,对 key 的值做--操作,并返回** @param string $key* @param int $value*/function decrement($key, $offset = 1){return self::$redis ? self::$redis->hIncrBy($key, 'data', -$offset) : false;}/*** 关闭rides** @param string $key* @param int $value*/public function close(){if (self::$redis) {return self::$redis->close ();self::$redis = null;}}}

这篇关于codeigniter的Redis使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/870004

相关文章

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

pdfmake生成pdf的使用

实际项目中有时会有根据填写的表单数据或者其他格式的数据,将数据自动填充到pdf文件中根据固定模板生成pdf文件的需求 文章目录 利用pdfmake生成pdf文件1.下载安装pdfmake第三方包2.封装生成pdf文件的共用配置3.生成pdf文件的文件模板内容4.调用方法生成pdf 利用pdfmake生成pdf文件 1.下载安装pdfmake第三方包 npm i pdfma

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

git使用的说明总结

Git使用说明 下载安装(下载地址) macOS: Git - Downloading macOS Windows: Git - Downloading Windows Linux/Unix: Git (git-scm.com) 创建新仓库 本地创建新仓库:创建新文件夹,进入文件夹目录,执行指令 git init ,用以创建新的git 克隆仓库 执行指令用以创建一个本地仓库的

【北交大信息所AI-Max2】使用方法

BJTU信息所集群AI_MAX2使用方法 使用的前提是预约到相应的算力卡,拥有登录权限的账号密码,一般为导师组共用一个。 有浏览器、ssh工具就可以。 1.新建集群Terminal 浏览器登陆10.126.62.75 (如果是1集群把75改成66) 交互式开发 执行器选Terminal 密码随便设一个(需记住) 工作空间:私有数据、全部文件 加速器选GeForce_RTX_2080_Ti

【Linux 从基础到进阶】Ansible自动化运维工具使用

Ansible自动化运维工具使用 Ansible 是一款开源的自动化运维工具,采用无代理架构(agentless),基于 SSH 连接进行管理,具有简单易用、灵活强大、可扩展性高等特点。它广泛用于服务器管理、应用部署、配置管理等任务。本文将介绍 Ansible 的安装、基本使用方法及一些实际运维场景中的应用,旨在帮助运维人员快速上手并熟练运用 Ansible。 1. Ansible的核心概念