CI框架中redis缓存相关操作文件示例代码


Posted in PHP onMay 17, 2016

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

redis缓存类文件位置:

'ci\system\libraries\Cache\drivers\Cache_redis.php'

<?php
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 5.2.4 or newer
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the Open Software License version 3.0
 *
 * This source file is subject to the Open Software License (OSL 3.0) that is
 * bundled with this package in the files license.txt / license.rst. It is
 * also available through the world wide web at this URL:
 * http://opensource.org/licenses/OSL-3.0
 * If you did not receive a copy of the license and are unable to obtain it
 * through the world wide web, please send an email to
 * licensing@ellislab.com so we can send you a copy immediately.
 *
 * @package   CodeIgniter
 * @author   EllisLab Dev Team
 * @copyright  Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
 * @license   http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
 * @link    http://codeigniter.com
 * @since    Version 3.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' => NULL,
    'port' => 6379,
    'timeout' => 0
    */
  );
  /**
   * Redis connection
   *
   * @var Redis
   */
  protected $_redis;
  /**
   * Get cache
   *
   * @param  string like *$key*
   * @return array(hash)
   */
  public function keys($key)
  {
    return $this->_redis->keys($key);
  }
  /**
   * Get cache
   *
   * @param  string Cache ID
   * @return mixed
   */
  public function get($key)
  {
    return $this->_redis->get($key);
  }
  /**
   * mGet cache
   *
   * @param  array  Cache ID Array
   * @return mixed
   */
  public function mget($keys)
  {
    return $this->_redis->mget($keys);
  }
  /**
   * 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)
  {
    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)
  {
    return ($this->_redis->delete($key) === 1);
  }
  /**
   * 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($key, $field, $value);
  }
  /**
   * 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($key, $field, $value);
  }
  /**
   * 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($key, $value)
  {
    return $this->_redis->lPush($key, $value);
  }
   /**
   * 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($key, $value)
  {
    return $this->_redis->rPush($key, $value);
  }
  /**
   * 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($key)
  {
    return $this->_redis->rPop($key);
  }
   /**
   * 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($key,$ontime=0)
  {
    return $this->_redis->brPop($key,$ontime);
  }
  /**
   * lLen a raw value
   *
   * @param  string $key  Cache ID
   * @return mixed  Value on success or FALSE on failure
   */
  public function llen($key)
  {
    return $this->_redis->lLen($key);
  }
  /**
   * 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->exists($id)
      ? $this->_redis->incr($id, $offset)
      : 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($key, $value = 1)
  {
    return $this->_redis->incrby($key, $value);
  }
  /**
   * 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($key, $seconds)
  {
    return $this->_redis->expire($key, $seconds);
  }
  /**
   * 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($alias,$key, $value)
  {
    return $this->_redis->hset($alias,$key, $value);
  }
  /**
   * 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($alias,$key)
  {
    return $this->_redis->hget($alias,$key);
  }
  /**
   * Increment a raw value
   *
   * @param  string $id Cache ID
   * @return mixed  New value on success or FALSE on failure
   */
  public function hkeys($alias)
  {
    return $this->_redis->hkeys($alias);
  }
  /**
   * 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($alias)
  {
    return $this->_redis->hgetall($alias);
  }
  /**
   * 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($alias,$key)
  {
    return $this->_redis->hmget($alias,$key);
  }
  /**
   * 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($alias,$key)
  {
    return $this->_redis->hdel($alias,$key);
  }
  /**
   * del a key value
   *
   * @param  string $id Cache ID
   * @return mixed  New value on success or FALSE on failure
   */
  public function hvals($alias)
  {
    return $this->_redis->hvals($alias);
  }
  /**
   * 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($alias,$array)
  {
    return $this->_redis->hmset($alias,$array);
  }
  /**
   * 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->exists($id)
      ? $this->_redis->decr($id, $offset)
      : 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($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'))
    {
      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()
  {
    $config = array();
    $CI =& get_instance();
    if ($CI->config->load('redis', TRUE, TRUE))
    {
      $config += $CI->config->item('redis');
    }
    $config = array_merge(self::$_default_config, $config);
    $config = !empty($config['redis'])?$config['redis']:$config;
    $this->_redis = new Redis();
    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']);
    }
    return TRUE;
  }
  /**
   * Class destructor
   *
   * Closes the connection to Redis if present.
   *
   * @return void
   */
  public function __destruct()
  {
    if ($this->_redis)
    {
      $this->_redis->close();
    }
  }
}
/* End of file Cache_redis.php */
/* Location: ./system/libraries/Cache/drivers/Cache_redis.php */

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

PHP 相关文章推荐
php FPDF类库应用实现代码
Mar 20 PHP
优化PHP代码技巧的小结
Jun 02 PHP
PHP编程风格规范分享
Jan 15 PHP
php stripslashes和addslashes的区别
Feb 03 PHP
采用thinkphp自带方法生成静态html文件详解
Jun 13 PHP
Java中final关键字详解
Aug 10 PHP
非常经典的PHP文件上传类分享
May 15 PHP
深入浅出讲解:php的socket通信原理
Dec 03 PHP
PHP排序二叉树基本功能实现方法示例
May 26 PHP
使用PHPWord生成word文档的方法详解
Jun 06 PHP
PHP判断函数是否被定义的方法
Jun 21 PHP
thinkphp框架实现路由重定义简化url访问地址的方法分析
Apr 04 PHP
Yii2如何批量添加数据
May 17 #PHP
PHP并发多进程处理利器Gearman使用介绍
May 16 #PHP
php截取视频指定帧为图片
May 16 #PHP
PHP中常用的数组操作方法笔记整理
May 16 #PHP
PHP获取用户访问IP地址的5种方法
May 16 #PHP
php pdo oracle中文乱码的快速解决方法
May 16 #PHP
Yii2中OAuth扩展及QQ互联登录实现方法
May 16 #PHP
You might like
深入解析php模板技术原理【一】
2008/01/10 PHP
两个开源的Php输出Excel文件类
2010/02/08 PHP
php UBB 解析实现代码
2011/11/27 PHP
简单谈谈PHP中strlen 函数
2016/02/27 PHP
浅谈PHP错误类型及屏蔽方法
2017/05/27 PHP
PHP迭代与递归实现无限级分类
2017/08/28 PHP
Extjs4 消息框去掉关闭按钮(类似Ext.Msg.alert)
2013/04/02 Javascript
jquery仿百度经验滑动切换浏览效果
2015/04/14 Javascript
JS利用cookie记忆当前位置的防刷新导航效果
2015/10/15 Javascript
详解Bootstrap的aria-label和aria-labelledby应用
2016/01/04 Javascript
jQuery 获取页面li数组并删除不在数组中的key
2016/08/02 Javascript
完美解决IE不支持Data.parse()的问题
2016/11/24 Javascript
微信小程序page的生命周期和音频播放及监听实例详解
2017/04/07 Javascript
JS去掉字符串前后空格、阻止表单提交的实现代码
2017/06/08 Javascript
手把手教你把nodejs部署到linux上跑出hello world
2017/06/19 NodeJs
node.js中使用Export和Import的方法
2017/09/18 Javascript
初识 Vue.js 中的 *.Vue文件
2017/11/22 Javascript
浅谈vue引入css,less遇到的坑和解决方法
2018/01/20 Javascript
vue+vue-router转场动画的实例代码
2018/09/01 Javascript
jQuery实现为动态添加的元素绑定事件实例分析
2018/09/07 jQuery
[02:07]2017国际邀请赛中国区预选赛直邀战队前瞻
2017/06/23 DOTA
[44:41]Fnatic vs Liquid 2018国际邀请赛小组赛BO2 第二场 8.16
2018/08/17 DOTA
深入理解python函数递归和生成器
2016/06/06 Python
详解安装mitmproxy以及遇到的坑和简单用法
2019/01/21 Python
tensorflow模型转ncnn的操作方式
2020/05/25 Python
HTML5 Canvas中绘制椭圆的4种方法
2015/04/24 HTML / CSS
巧用HTML5给按钮背景设计不同的动画简单实例
2016/08/09 HTML / CSS
iframe与window.onload如何使用详解
2020/05/07 HTML / CSS
司机辞职报告范文
2014/01/20 职场文书
公司晚会策划方案
2014/05/17 职场文书
领导班子四风对照检查材料范文
2014/09/27 职场文书
单位实习介绍信
2015/05/05 职场文书
乡镇干部学习心得体会
2016/01/23 职场文书
2016年万圣节活动个人总结
2016/04/05 职场文书
pytorch中[..., 0]的用法说明
2021/05/20 Python
SpringCloud中分析讲解Feign组件添加请求头有哪些坑梳理
2022/06/21 Java/Android