lang/php

PHP RedisClient Class

C/H 2016. 6. 7. 18:22



/* 
 * 20160607
 * http://bluebreeze.co.kr/978
 * required php-redis
 */

define('ENVIRONMENT', 'testing');
define('REDIS_HOST', 'localhost');
define('REDIS_PORT', 6379);

class RedisClient {

	private $isCache = FALSE;
	private $redis = FALSE;

	private $key = 'Cache';
	private $cachedKey = Array();
	private $setCachedKey = Array();

	public function __construct(){
		
		if( class_exists('Redis') )
		{
			return FALSE;
		}

		try {
			$this->redis = new Redis();

			if( $this->connect( REDIS_HOST, REDIS_PORT ) )
			{
				@header( "Chache Driver : TRUE" );
				$this->isCache = TRUE;
			}
			else
			{
				Throw New Exception('');
			}
		} catch (Exception $e) {
			@header( "Chache Driver : FALSE" );
		}
	}

	public function getKey( $key='' )
	{
		return $this->key.':'.str_replace("-", '', $key);
	}

	public function setIsCache( $isCache=FALSE )
	{
		$this->isCache = $isCache;
	}

	public function connect( $host='localhost', $port=6379 )
	{
		if( ! $this->redis )
		{
			return FALSE;
		}

		return $this->redis->connect( $host, $port );
	}

	public function set( $key='', $val='', $ttl=3600 )  // default 3600s:1hour
	{
		if( ! $this->redis || ! $this->isCache || empty($key) || empty($val) )
		{
			return FALSE;
		}

		try{
			$key = $this->getKey( $key );

			if( $this->redis->set( $key, json_encode($val), $ttl ))
			{
				array_push( $this->setCachedKey, $key );
				@header("setCached : ".join(', ', $this->setCachedKey) );
				return TRUE;
			}

			return FALSE;

		}catch(Exception $e){
			if( ENVIRONMENT != 'production' )
			{
				echo $e->getMessage().':'.$e->getCode().':'.__LINE__;
			}
			return FALSE;
		}
	}

	public function get( $key='' )
	{
		if( ! $this->redis || ! $this->isCache || empty($key) )
		{
			return FALSE;
		}

		try{
			$key = $this->getKey( $key );

			$cached = $this->redis->get( $key );
			if( $cached )
			{
				array_push( $this->cachedKey, $key );
				@header("isCached : ".join(', ', $this->cachedKey) );
			}

			return json_decode($cached);

		}catch(Exception $e){
			if( ENVIRONMENT != 'production' )
			{
				echo $e->getMessage().':'.$e->getCode().':'.__LINE__;
			}
			return FALSE;
		}
	}
}


/* How To
$redis = new RedisClient();
$rKey = "key";
if( $return = $redis->get( $rKey ) )
{
	return $return;
}

$return = Array();

$redis->set( $rKey, $return );
return $return;
*/


반응형

'lang > php' 카테고리의 다른 글

php7.1 mcrypt_get_iv_size Error  (0) 2017.02.17
CI hwp 파일 업로드 (unknown file extension upload), 다운로드  (0) 2016.07.02
PHP Redis  (0) 2016.06.03
composer codeigniter  (0) 2016.04.12
php7 opcache.enable 설정  (0) 2016.04.05