1: <?php
2: /**
3: * CRedisCache class file
4: *
5: * @author Carsten Brandt <mail@cebe.cc>
6: * @link http://www.yiiframework.com/
7: * @copyright 2008-2013 Yii Software LLC
8: * @license http://www.yiiframework.com/license/
9: */
10:
11: /**
12: * CRedisCache implements a cache application component based on {@link http://redis.io/ redis}.
13: *
14: * CRedisCache needs to be configured with {@link hostname}, {@link port} and {@link database} of the server
15: * to connect to. By default CRedisCache assumes there is a redis server running on localhost at
16: * port 6379 and uses the database number 0.
17: *
18: * CRedisCache also supports {@link http://redis.io/commands/auth the AUTH command} of redis.
19: * When the server needs authentication, you can set the {@link password} property to
20: * authenticate with the server after connect.
21: *
22: * See {@link CCache} manual for common cache operations that are supported by CRedisCache.
23: *
24: * To use CRedisCache as the cache application component, configure the application as follows,
25: * <pre>
26: * array(
27: * 'components'=>array(
28: * 'cache'=>array(
29: * 'class'=>'CRedisCache',
30: * 'hostname'=>'localhost',
31: * 'port'=>6379,
32: * 'database'=>0,
33: * ),
34: * ),
35: * )
36: * </pre>
37: *
38: * The minimum required redis version is 2.0.0.
39: *
40: * @author Carsten Brandt <mail@cebe.cc>
41: * @package system.caching
42: * @since 1.1.14
43: */
44: class CRedisCache extends CCache
45: {
46: /**
47: * @var string hostname to use for connecting to the redis server. Defaults to 'localhost'.
48: */
49: public $hostname='localhost';
50: /**
51: * @var int the port to use for connecting to the redis server. Default port is 6379.
52: */
53: public $port=6379;
54: /**
55: * @var string the password to use to authenticate with the redis server. If not set, no AUTH command will be sent.
56: */
57: public $password;
58: /**
59: * @var int the redis database to use. This is an integer value starting from 0. Defaults to 0.
60: */
61: public $database=0;
62: /**
63: * @var float timeout to use for connection to redis. If not set the timeout set in php.ini will be used: ini_get("default_socket_timeout")
64: */
65: public $timeout=null;
66: /**
67: * @var resource redis socket connection
68: */
69: private $_socket;
70:
71: /**
72: * Establishes a connection to the redis server.
73: * It does nothing if the connection has already been established.
74: * @throws CException if connecting fails
75: */
76: protected function connect()
77: {
78: $this->_socket=@stream_socket_client(
79: $this->hostname.':'.$this->port,
80: $errorNumber,
81: $errorDescription,
82: $this->timeout ? $this->timeout : ini_get("default_socket_timeout")
83: );
84: if ($this->_socket)
85: {
86: if($this->password!==null)
87: $this->executeCommand('AUTH',array($this->password));
88: $this->executeCommand('SELECT',array($this->database));
89: }
90: else
91: throw new CException('Failed to connect to redis: '.$errorDescription,(int)$errorNumber);
92: }
93:
94: /**
95: * Executes a redis command.
96: * For a list of available commands and their parameters see {@link http://redis.io/commands}.
97: *
98: * @param string $name the name of the command
99: * @param array $params list of parameters for the command
100: * @return array|bool|null|string Dependend on the executed command this method
101: * will return different data types:
102: * <ul>
103: * <li><code>true</code> for commands that return "status reply".</li>
104: * <li><code>string</code> for commands that return "integer reply"
105: * as the value is in the range of a signed 64 bit integer.</li>
106: * <li><code>string</code> or <code>null</code> for commands that return "bulk reply".</li>
107: * <li><code>array</code> for commands that return "Multi-bulk replies".</li>
108: * </ul>
109: * See {@link http://redis.io/topics/protocol redis protocol description}
110: * for details on the mentioned reply types.
111: * @throws CException for commands that return {@link http://redis.io/topics/protocol#error-reply error reply}.
112: */
113: public function executeCommand($name,$params=array())
114: {
115: if($this->_socket===null)
116: $this->connect();
117:
118: array_unshift($params,$name);
119: $command='*'.count($params)."\r\n";
120: foreach($params as $arg)
121: $command.='$'.strlen($arg)."\r\n".$arg."\r\n";
122:
123: fwrite($this->_socket,$command);
124:
125: return $this->parseResponse(implode(' ',$params));
126: }
127:
128: /**
129: * Reads the result from socket and parses it
130: * @return array|bool|null|string
131: * @throws CException socket or data problems
132: */
133: private function parseResponse()
134: {
135: if(($line=fgets($this->_socket))===false)
136: throw new CException('Failed reading data from redis connection socket.');
137: $type=$line[0];
138: $line=substr($line,1,-2);
139: switch($type)
140: {
141: case '+': // Status reply
142: return true;
143: case '-': // Error reply
144: throw new CException('Redis error: '.$line);
145: case ':': // Integer reply
146: // no cast to int as it is in the range of a signed 64 bit integer
147: return $line;
148: case '$': // Bulk replies
149: if($line=='-1')
150: return null;
151: $length=$line+2;
152: $data='';
153: while($length>0)
154: {
155: if(($block=fread($this->_socket,$length))===false)
156: throw new CException('Failed reading data from redis connection socket.');
157: $data.=$block;
158: $length-=(function_exists('mb_strlen') ? mb_strlen($block,'8bit') : strlen($block));
159: }
160: return substr($data,0,-2);
161: case '*': // Multi-bulk replies
162: $count=(int)$line;
163: $data=array();
164: for($i=0;$i<$count;$i++)
165: $data[]=$this->parseResponse();
166: return $data;
167: default:
168: throw new CException('Unable to parse data received from redis.');
169: }
170: }
171:
172: /**
173: * Retrieves a value from cache with a specified key.
174: * This is the implementation of the method declared in the parent class.
175: * @param string $key a unique key identifying the cached value
176: * @return string|boolean the value stored in cache, false if the value is not in the cache or expired.
177: */
178: protected function getValue($key)
179: {
180: return $this->executeCommand('GET',array($key));
181: }
182:
183: /**
184: * Retrieves multiple values from cache with the specified keys.
185: * @param array $keys a list of keys identifying the cached values
186: * @return array a list of cached values indexed by the keys
187: */
188: protected function getValues($keys)
189: {
190: $response=$this->executeCommand('MGET',$keys);
191: $result=array();
192: $i=0;
193: foreach($keys as $key)
194: $result[$key]=$response[$i++];
195: return $result;
196: }
197:
198: /**
199: * Stores a value identified by a key in cache.
200: * This is the implementation of the method declared in the parent class.
201: *
202: * @param string $key the key identifying the value to be cached
203: * @param string $value the value to be cached
204: * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
205: * @return boolean true if the value is successfully stored into cache, false otherwise
206: */
207: protected function setValue($key,$value,$expire)
208: {
209: if ($expire==0)
210: return (bool)$this->executeCommand('SET',array($key,$value));
211: return (bool)$this->executeCommand('SETEX',array($key,$expire,$value));
212: }
213:
214: /**
215: * Stores a value identified by a key into cache if the cache does not contain this key.
216: * This is the implementation of the method declared in the parent class.
217: *
218: * @param string $key the key identifying the value to be cached
219: * @param string $value the value to be cached
220: * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
221: * @return boolean true if the value is successfully stored into cache, false otherwise
222: */
223: protected function addValue($key,$value,$expire)
224: {
225: if ($expire == 0)
226: return (bool)$this->executeCommand('SETNX',array($key,$value));
227:
228: if($this->executeCommand('SETNX',array($key,$value)))
229: {
230: $this->executeCommand('EXPIRE',array($key,$expire));
231: return true;
232: }
233: else
234: return false;
235: }
236:
237: /**
238: * Deletes a value with the specified key from cache
239: * This is the implementation of the method declared in the parent class.
240: * @param string $key the key of the value to be deleted
241: * @return boolean if no error happens during deletion
242: */
243: protected function deleteValue($key)
244: {
245: return (bool)$this->executeCommand('DEL',array($key));
246: }
247:
248: /**
249: * Deletes all values from cache.
250: * This is the implementation of the method declared in the parent class.
251: * @return boolean whether the flush operation was successful.
252: */
253: protected function flushValues()
254: {
255: return $this->executeCommand('FLUSHDB');
256: }
257: }
258: