웹 프론트엔드 JS 튜토리얼 CI框架中redis缓存相关操作文件示例代码_php实例

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

Jun 07, 2016 pm 05:07 PM
CI 프레임워크 레디스 캐시

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

redis缓存类文件位置:

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

<&#63;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)
      &#63; $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)
      &#63; $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)
      &#63; $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'])&#63;$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相关内容感兴趣的读者可查看本站专题:《codeigniter入门教程》、《CI(CodeIgniter)框架进阶教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《php缓存技术总结》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

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

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

PHP에서 CI 프레임워크를 사용하는 방법은 무엇입니까? PHP에서 CI 프레임워크를 사용하는 방법은 무엇입니까? Jun 01, 2023 am 08:48 AM

네트워크 기술의 발전으로 PHP는 웹 개발을 위한 중요한 도구 중 하나가 되었습니다. 인기 있는 PHP 프레임워크 중 하나인 CodeIgniter(이하 CI)도 점점 더 많은 관심과 사용을 받고 있습니다. 오늘은 CI 프레임워크를 활용하는 방법에 대해 살펴보겠습니다. 1. CI 프레임워크 설치 먼저 CI 프레임워크를 다운로드하여 설치해야 합니다. CI 공식 홈페이지(https://codeigniter.com/)에서 최신 버전의 CI 프레임워크 압축 패키지를 다운로드하세요. 다운로드가 완료되면 압축을 풀어주세요

PHP 개발 팁: Redis를 사용하여 MySQL 쿼리 결과를 캐시하는 방법 PHP 개발 팁: Redis를 사용하여 MySQL 쿼리 결과를 캐시하는 방법 Jul 02, 2023 pm 03:30 PM

PHP 개발 팁: Redis를 사용하여 MySQL 쿼리 결과를 캐시하는 방법 소개: 웹 개발 과정에서 데이터베이스 쿼리는 일반적인 작업 중 하나입니다. 그러나 데이터베이스 쿼리를 자주 수행하면 성능 문제가 발생하고 웹 페이지 로딩 속도에 영향을 줄 수 있습니다. 쿼리 효율성을 높이기 위해 Redis를 캐시로 사용하고 자주 쿼리되는 데이터를 Redis에 넣어서 MySQL에 대한 쿼리 수를 줄이고 웹 페이지의 응답 속도를 향상시킬 수 있습니다. 이 기사에서는 Redis를 사용하여 MySQL 쿼리 결과를 캐시하는 방법의 개발을 소개합니다.

PHP에서 CI 프레임워크를 사용하는 방법 PHP에서 CI 프레임워크를 사용하는 방법 Jun 27, 2023 pm 04:51 PM

PHP는 웹 개발에 널리 사용되는 인기 있는 프로그래밍 언어입니다. CI(CodeIgniter) 프레임워크는 PHP에서 가장 널리 사용되는 프레임워크 중 하나입니다. 이는 기성 도구 및 기능 라이브러리의 전체 세트는 물론 일부 인기 있는 디자인 패턴을 제공하여 개발자가 웹 애플리케이션을 보다 효율적으로 개발할 수 있도록 합니다. 이 기사에서는 CI 프레임워크를 사용하여 PHP 애플리케이션을 개발하는 기본 단계와 방법을 소개합니다. CI 프레임워크의 기본 개념과 구조를 이해합니다. CI 프레임워크를 사용하기 전에 몇 가지 기본 개념과 구조를 이해해야 합니다. 아래에

사물 인터넷에서의 Redis 적용 탐색 사물 인터넷에서의 Redis 적용 탐색 Nov 07, 2023 am 11:36 AM

사물 인터넷에서의 Redis 적용 탐색 오늘날 사물 인터넷(IoT)이 급속히 발전하는 시대에는 수많은 장치가 서로 연결되어 풍부한 데이터 리소스를 제공합니다. 사물 인터넷(Internet of Things)의 적용이 점점 더 널리 보급됨에 따라 대규모 데이터의 처리 및 저장은 해결해야 할 시급한 문제가 되었습니다. 고성능 메모리 데이터 스토리지 시스템인 Redis는 뛰어난 데이터 처리 기능과 낮은 대기 시간을 갖추고 있어 IoT 애플리케이션에 많은 이점을 제공합니다. Redis는 개방형입니다.

PHP에서 CI4 프레임워크를 사용하는 방법은 무엇입니까? PHP에서 CI4 프레임워크를 사용하는 방법은 무엇입니까? Jun 01, 2023 pm 02:40 PM

PHP는 널리 사용되는 서버측 스크립팅 언어이며 CodeIgniter4(CI4)는 웹 애플리케이션을 구축하는 빠르고 우수한 방법을 제공하는 인기 있는 PHP 프레임워크입니다. 이 기사에서는 CI4 프레임워크를 사용하여 뛰어난 웹 애플리케이션을 개발하는 방법을 단계별로 안내해 드립니다. 1. CI4 다운로드 및 설치 먼저 공식 웹사이트(https://codeigniter.com/downloa)에서 다운로드해야 합니다.

PHP의 CI 프레임워크 가이드 PHP의 CI 프레임워크 가이드 May 22, 2023 pm 07:10 PM

인터넷이 발전하고 인터넷이 사람들의 삶에 지속적으로 통합됨에 따라 네트워크 애플리케이션의 개발이 점점 더 중요해지고 있습니다. 잘 알려진 프로그래밍 언어인 PHP는 인터넷 애플리케이션 개발에 선호되는 언어 중 하나가 되었습니다. 개발자는 수많은 PHP 프레임워크를 사용하여 개발 프로세스를 단순화할 수 있으며, 가장 널리 사용되는 프레임워크 중 하나는 CodeIgniter(CI) 프레임워크입니다. CI는 강력한 PHP 웹 애플리케이션 프레임워크로, 가볍고 사용하기 쉬우며 성능이 최적화되어 개발자가 빠르게 구축할 수 있다는 특징을 가지고 있습니다.

Golang의 메모리 캐시와 Redis 캐시의 차이점과 장단점을 분석합니다. Golang의 메모리 캐시와 Redis 캐시의 차이점과 장단점을 분석합니다. Jun 19, 2023 pm 09:28 PM

애플리케이션의 크기가 계속 증가함에 따라 데이터에 대한 필요성도 커지고 있습니다. 데이터를 읽고 쓰는 최적화된 방법인 캐싱은 최신 애플리케이션의 필수적인 부분이 되었습니다. 캐시 선택 측면에서 Golang의 내장 메모리 캐시와 Redis 캐시가 비교적 일반적인 선택입니다. 이 글에서는 독자들이 보다 적절한 선택을 할 수 있도록 두 가지를 비교 분석할 것입니다. 1. 메모리 캐시와 Redis 캐시의 차이점 메모리 캐시와 Redis 캐시의 가장 큰 차이점은 데이터 지속성입니다.

CI 프레임워크에 CSS를 도입하는 방법 CI 프레임워크에 CSS를 도입하는 방법 Dec 26, 2023 pm 05:20 PM

CI 프레임워크에 CSS 스타일을 도입하는 단계는 다음과 같습니다. 1. CSS 파일을 준비합니다. 2. CSS 파일을 CI 프레임워크 프로젝트의 적절한 위치에 저장합니다. 3. CSS 스타일을 사용해야 하는 페이지에 CSS를 도입합니다. HTML <link> 태그 파일을 통해 4. HTML 요소에 CSS 클래스 또는 ID 이름을 사용하여 해당 스타일을 적용합니다.

See all articles