Codeigniter的Redis使用
一、Redis的配置和简单使用1:
1. ./config/redis.php
:
<?php
$config['redis_host'] = '127.0.0.1';
$config['redis_port'] = '6379';
$config['redis_isopen'] = true;
2. ./config/config.php
:
require_once(APPPATH . "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(
'cache_apc', 'cache_file', 'cache_memcached', 'cache_dummy', 'cache_redis'
);
//添加:
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 - 2016, 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. (https://ellislab.com/)
* @copyright Copyright (c) 2014 - 2016, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://opensource.org/licenses/MIT MIT License
* @link https://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(
'host' => '10.19.108.196',
'password' => 'datu@com',
'port' => 6379,
'timeout' => 0
);
/**
* Redis connection
*
* @var Redis
*/
protected $_redis;
// ------------------------------------------------------------------------
/**
* Class constructor
*
* Setup Redis
*
* Loads Redis config file if present. Will halt execution
* if a Redis connection can't be established.
*
* @return void
* @see Redis::connect()
*/
public function __construct(){
if ( ! $this->is_supported()){
log_message('error', 'Cache: Failed to create Redis object; extension not loaded?');
return;
}
$CI =& get_instance();
// 读取配置文件
$config_all = get_config();
$config['host'] = $config_all['redis_host'];
$config['port'] = $config_all['redis_port'];
// $config['password'] = $config_all['redis_pwd'];
$config['timeout'] = 0;
$this->_redis = new Redis();
try{
if ( ! $this->_redis->connect($config['host'], ($config['host'][0] === '/' ? 0 : $config['port']), $config['timeout'])){
log_message('error', 'Cache: Redis connection failed. Check your configuration.');
}
if (isset($config['password']) && ! $this->_redis->auth($config['password'])){
log_message('error', 'Cache: Redis authentication failed.');
}
}
catch (RedisException $e){
log_message('error', 'Cache: Redis connection refused ('.$e->getMessage().')');
}
}
// ------------------------------------------------------------------------
/**
* Get cache
*
* @param string $key Cache ID
* @return mixed
*/
public function get($key){
$data = $this->_redis->hMGet($key, array('__ci_type', '__ci_value'));
if (!$data['__ci_type']) $data['__ci_type'] = 'integer';
if ( ! isset($data['__ci_type'], $data['__ci_value']) OR $data['__ci_value'] === FALSE){
return FALSE;
}
switch ($data['__ci_type']){
case 'array':
case 'object':
return unserialize($data['__ci_value']);
case 'boolean':
case 'integer':
case 'double': // Yes, 'double' is returned and NOT 'float'
case 'string':
case 'NULL':
return settype($data['__ci_value'], $data['__ci_type'])
? $data['__ci_value']
: FALSE;
case 'resource':
default:
return FALSE;
}
}
// ------------------------------------------------------------------------
/**
* 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){
switch ($data_type = gettype($data)){
case 'array':
case 'object':
$data = serialize($data);
break;
case 'boolean':
case 'integer':
case 'double': // Yes, 'double' is returned and NOT 'float'
case 'string':
case 'NULL':
break;
case 'resource':
default:
return FALSE;
}
if ( ! $this->_redis->hMSet($id, array('__ci_type' => $data_type, '__ci_value' => $data))){
return FALSE;
}elseif ($ttl){
$this->_redis->expireAt($id, time() + $ttl);
}
return TRUE;
}
// ------------------------------------------------------------------------
/**
* Delete from cache
*
* @param string $key Cache key
* @return bool
*/
public function delete($key){
return ($this->_redis->delete($key) === 1);
}
// ------------------------------------------------------------------------
/**
* 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->hIncrBy($id, '__ci_value', $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->hIncrBy($id, '__ci_value', -$offset);
}
// ------------------------------------------------------------------------
/**
* Clean cache
*
* @return bool
* @see Redis::flushDB()
*/
public function clean(){
return $this->_redis->flushDB();
}
// ------------------------------------------------------------------------
/**
* Get cache driver info
*
* @param string $type 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 $key Cache key
* @return array
*/
public function get_metadata($key){
$value = $this->get($key);
if ($value !== FALSE){
return array(
'expire' => time() + $this->_redis->ttl($key),
'data' => $value
);
}
return FALSE;
}
// ------------------------------------------------------------------------
/**
* Check if Redis driver is supported
*
* @return bool
*/
public function is_supported(){
return extension_loaded('redis');
}
// ------------------------------------------------------------------------
/**
* return redis
*
* @return redis
*/
public function get_redis(){
return $this->_redis;
}
// ------------------------------------------------------------------------
/**
* Class destructor
*
* Closes the connection to Redis if present.
*
* @return void
*/
public function __destruct(){
if ($this->_redis){
$this->_redis->close();
}
}
}
6. 控制器中就可以使用啦:
//初始化:
$this->load->library('redisservice');
$this->redis = new RedisService;
//使用:
$this->redis->redis->set('name', 'chenjian');
$this->redis->redis->get('name');
二、Redis的实际使用2:
对于一个数据的请求,一般情况下controller中接收参数
$this->input->get('date')
,然后通过参数请求model里面的方法从而得到数据返回,这一层可以做缓存:
~示例~:
- 控制器中:****
$this->load->model("user"); //初始化
$this->load->library( 'cache_mgr' ); //引用cache_mgr库文件
function user_list(){
$age = $this->input->get('age');
$key = sprintf('2017-01-12-%s', $age); //利用日期+年龄组成一个key。
/*
get_cache有四个参数:get_cache(key, model里面的方法, 参数数组, 缓存的时长),且get_cache方法不仅仅可以取缓存,如果没有缓存就执行model里面的方法,并且缓存。
*/
$data = $this->cache_mgr->get_cache($key, array($this->user, 'get_user'), array('age' => $age), 60 * 60);
}
- library里面的库文件:
<?php
class cache_mgr{
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使用的更多相关文章
- codeigniter使用mongodb/redis
ci2.x版本,使用mongodb,需要安装pecl-php-mongo扩展(github上很多扩展已不可用,找到个可用版本纪录于此),添加到php.ini中 使用如下 public function ...
- **【ci框架】精通CodeIgniter框架
http://blog.csdn.net/yanhui_wei/article/details/25803945 一.大纲 1.codeigniter框架的授课内容安排 2.codeigniter框架 ...
- 使用redis构建可靠分布式锁
关于分布式锁的概念,具体实现方式,直接参阅下面两个帖子,这里就不多介绍了. 分布式锁的多种实现方式 分布式锁总结 对于分布式锁的几种实现方式的优劣,这里再列举下 1. 数据库实现方式 优点:易理解 缺 ...
- Ignite性能测试以及对redis的对比
测试方法 为了对Ignite做一个基本了解,做了一个性能测试,测试方法也比较简单主要是针对client模式,因为这种方法和使用redis的方式特别像.测试方法很简单主要是下面几点: 不作参数优化,默认 ...
- mac osx 安装redis扩展
1 php -v查看php版本 2 brew search php|grep redis 搜索对应的redis ps:如果没有brew 就根据http://brew.sh安装 3 brew ins ...
- Redis/HBase/Tair比较
KV系统对比表 对比维度 Redis Redis Cluster Medis Hbase Tair 访问模式 支持Value大小 理论上不超过1GB(建议不超过1MB) 理论上可配置(默认配置1 ...
- Redis数据库
Redis是k-v型数据库的典范,设计思想及数据结构实现都值得学习. 1.数据类型 value支持五种数据类型:1.字符串(strings)2.字符串列表(lists)3.字符串集合(sets)4.有 ...
- redis 学习笔记(2)
redis-cluster 简介 redis-cluster是一个分布式.容错的redis实现,redis-cluster通过将各个单独的redis实例通过特定的协议连接到一起实现了分布式.集群化的目 ...
- redis 学习笔记(1)
redis持久化 snapshot数据快照(rdb) 这是一种定时将redis内存中的数据写入磁盘文件的一种方案,这样保留这一时刻redis中的数据镜像,用于意外回滚.redis的snapshot的格 ...
随机推荐
- wpf 遍历控件及其值
/// <summary> /// 遍历控件及其值 /// </summary> /// <param name="uiControls">界面 ...
- delphi 2010与delphi XE破解版的冲突
在系统中同时安装了Dephi 2010LITE版与Delphi XE lite后,总是会有一个有问题 是因为两者都是读取C:\ProgramData\Embarcadero目录下的license文件, ...
- MyEclipse10--的使用经验
MyEclipse10--的使用经验总结 ------------------ 1.MyEclipse中的验证validation----->>用MyEclipse做ExtJs项目研发的时 ...
- 借助JavaScript中的时间函数改变Html中Table边框的颜色
借助JavaScript中的时间函数改变Html中Table边框的颜色 <html> <head> <meta http-equiv="Content-Type ...
- Unity游戏开发中的内存管理_资料
内存是手游的硬伤——Unity游戏Mono内存管理及泄漏http://wetest.qq.com/lab/view/135.html 深入浅出再谈Unity内存泄漏http://wetest.qq.c ...
- android中导入低版本project可能会遇到的编译问题(转自: Victor@Beijing)
使用高版本的SDK后再导入以前用低版本的project时,会遇到一些兼容性的问题. (1)Unable to resolve target 'android-5' 因为本机中现在使用的是2.2的SDK ...
- .NET开源资源汇总
1>> 力软信息化系统快速开发框架 2>> 金碟友商网 3>>
- php文件锁
前言 1.锁机制之所以存在是因为并发问题导致的资源竞争,为了确保操作的有效性和完整性,可以通过锁机制将并发状态转换成串行状态.作为锁机制中的一种,PHP 的文件锁也是为了应对资源竞争.假设一个应用场景 ...
- keras安装
找对工具真的很重要,周末和学霸折腾了一天才装了几个包,问了同事找了一个方便的包,装起来不要太快啊.二十分钟全部搞定. 一.Anaconda 真是大杀器,牛到飞起来,一键部署,所有常用的机器学习包全部包 ...
- XP安装IIS来加载aspx页面(Web调用SAP数据)
1,安装IIS 在XP中安装IIS方法很简单,安装时需要提供安装光盘来加载I386文件,可以使用虚拟光驱或光盘.在此做个简单说明(控制面板-添加/删除 Windows组件-勾选Internet信息服务 ...