3 * Object caching using Redis (http://redis.io/).
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 class RedisBagOStuff
extends BagOStuff
{
24 /** @var RedisConnectionPool */
26 /** @var array List of server names */
29 protected $automaticFailover;
32 * Construct a RedisBagOStuff object. Parameters are:
34 * - servers: An array of server names. A server name may be a hostname,
35 * a hostname/port combination or the absolute path of a UNIX socket.
36 * If a hostname is specified but no port, the standard port number
37 * 6379 will be used. Required.
39 * - connectTimeout: The timeout for new connections, in seconds. Optional,
40 * default is 1 second.
42 * - persistent: Set this to true to allow connections to persist across
43 * multiple web requests. False by default.
45 * - password: The authentication password, will be sent to Redis in
46 * clear text. Optional, if it is unspecified, no AUTH command will be
49 * - automaticFailover: If this is false, then each key will be mapped to
50 * a single server, and if that server is down, any requests for that key
51 * will fail. If this is true, a connection failure will cause the client
52 * to immediately try the next server in the list (as determined by a
53 * consistent hashing algorithm). True by default. This has the
54 * potential to create consistency issues if a server is slow enough to
55 * flap, for example if it is in swap death.
56 * @param array $params
58 function __construct( $params ) {
59 $redisConf = array( 'serializer' => 'none' ); // manage that in this class
60 foreach ( array( 'connectTimeout', 'persistent', 'password' ) as $opt ) {
61 if ( isset( $params[$opt] ) ) {
62 $redisConf[$opt] = $params[$opt];
65 $this->redisPool
= RedisConnectionPool
::singleton( $redisConf );
67 $this->servers
= $params['servers'];
68 if ( isset( $params['automaticFailover'] ) ) {
69 $this->automaticFailover
= $params['automaticFailover'];
71 $this->automaticFailover
= true;
75 public function get( $key, &$casToken = null ) {
77 list( $server, $conn ) = $this->getConnection( $key );
82 $value = $conn->get( $key );
84 $result = $this->unserialize( $value );
85 } catch ( RedisException
$e ) {
87 $this->handleException( $conn, $e );
90 $this->logRequest( 'get', $key, $server, $result );
94 public function set( $key, $value, $expiry = 0 ) {
96 list( $server, $conn ) = $this->getConnection( $key );
100 $expiry = $this->convertToRelative( $expiry );
103 $result = $conn->setex( $key, $expiry, $this->serialize( $value ) );
105 // No expiry, that is very different from zero expiry in Redis
106 $result = $conn->set( $key, $this->serialize( $value ) );
108 } catch ( RedisException
$e ) {
110 $this->handleException( $conn, $e );
113 $this->logRequest( 'set', $key, $server, $result );
117 public function cas( $casToken, $key, $value, $expiry = 0 ) {
119 list( $server, $conn ) = $this->getConnection( $key );
123 $expiry = $this->convertToRelative( $expiry );
125 $conn->watch( $key );
127 if ( $this->serialize( $this->get( $key ) ) !== $casToken ) {
132 // multi()/exec() will fail atomically if the key changed since watch()
135 $conn->setex( $key, $expiry, $this->serialize( $value ) );
137 // No expiry, that is very different from zero expiry in Redis
138 $conn->set( $key, $this->serialize( $value ) );
140 $result = ( $conn->exec() == array( true ) );
141 } catch ( RedisException
$e ) {
143 $this->handleException( $conn, $e );
146 $this->logRequest( 'cas', $key, $server, $result );
150 public function delete( $key, $time = 0 ) {
152 list( $server, $conn ) = $this->getConnection( $key );
157 $conn->delete( $key );
158 // Return true even if the key didn't exist
160 } catch ( RedisException
$e ) {
162 $this->handleException( $conn, $e );
165 $this->logRequest( 'delete', $key, $server, $result );
169 public function getMulti( array $keys ) {
173 foreach ( $keys as $key ) {
174 list( $server, $conn ) = $this->getConnection( $key );
178 $conns[$server] = $conn;
179 $batches[$server][] = $key;
182 foreach ( $batches as $server => $batchKeys ) {
183 $conn = $conns[$server];
185 $conn->multi( Redis
::PIPELINE
);
186 foreach ( $batchKeys as $key ) {
189 $batchResult = $conn->exec();
190 if ( $batchResult === false ) {
191 $this->debug( "multi request to $server failed" );
194 foreach ( $batchResult as $i => $value ) {
195 if ( $value !== false ) {
196 $result[$batchKeys[$i]] = $this->unserialize( $value );
199 } catch ( RedisException
$e ) {
200 $this->handleException( $conn, $e );
204 $this->debug( "getMulti for " . count( $keys ) . " keys " .
205 "returned " . count( $result ) . " results" );
214 public function setMulti( array $data, $expiry = 0 ) {
218 foreach ( $data as $key => $value ) {
219 list( $server, $conn ) = $this->getConnection( $key );
223 $conns[$server] = $conn;
224 $batches[$server][] = $key;
227 $expiry = $this->convertToRelative( $expiry );
229 foreach ( $batches as $server => $batchKeys ) {
230 $conn = $conns[$server];
232 $conn->multi( Redis
::PIPELINE
);
233 foreach ( $batchKeys as $key ) {
235 $conn->setex( $key, $expiry, $this->serialize( $data[$key] ) );
237 $conn->set( $key, $this->serialize( $data[$key] ) );
240 $batchResult = $conn->exec();
241 if ( $batchResult === false ) {
242 $this->debug( "setMulti request to $server failed" );
245 foreach ( $batchResult as $value ) {
246 if ( $value === false ) {
250 } catch ( RedisException
$e ) {
251 $this->handleException( $server, $conn, $e );
261 public function add( $key, $value, $expiry = 0 ) {
263 list( $server, $conn ) = $this->getConnection( $key );
267 $expiry = $this->convertToRelative( $expiry );
271 $conn->setnx( $key, $this->serialize( $value ) );
272 $conn->expire( $key, $expiry );
273 $result = ( $conn->exec() == array( true, true ) );
275 $result = $conn->setnx( $key, $this->serialize( $value ) );
277 } catch ( RedisException
$e ) {
279 $this->handleException( $conn, $e );
282 $this->logRequest( 'add', $key, $server, $result );
287 * Non-atomic implementation of incr().
289 * Probably all callers actually want incr() to atomically initialise
290 * values to zero if they don't exist, as provided by the Redis INCR
291 * command. But we are constrained by the memcached-like interface to
292 * return null in that case. Once the key exists, further increments are
294 * @param string $key Key to increase
295 * @param int $value Value to add to $key (Default 1)
296 * @return int|bool New value or false on failure
298 public function incr( $key, $value = 1 ) {
300 list( $server, $conn ) = $this->getConnection( $key );
304 if ( !$conn->exists( $key ) ) {
308 $result = $conn->incrBy( $key, $value );
309 } catch ( RedisException
$e ) {
311 $this->handleException( $conn, $e );
314 $this->logRequest( 'incr', $key, $server, $result );
321 protected function serialize( $data ) {
322 // Serialize anything but integers so INCR/DECR work
323 // Do not store integer-like strings as integers to avoid type confusion (bug 60563)
324 return is_int( $data ) ?
$data : serialize( $data );
328 * @param string $data
331 protected function unserialize( $data ) {
332 return ctype_digit( $data ) ?
intval( $data ) : unserialize( $data );
336 * Get a Redis object with a connection suitable for fetching the specified key
338 * @return array (server, RedisConnRef) or (false, false)
340 protected function getConnection( $key ) {
341 if ( count( $this->servers
) === 1 ) {
342 $candidates = $this->servers
;
344 $candidates = $this->servers
;
345 ArrayUtils
::consistentHashSort( $candidates, $key, '/' );
346 if ( !$this->automaticFailover
) {
347 $candidates = array_slice( $candidates, 0, 1 );
351 foreach ( $candidates as $server ) {
352 $conn = $this->redisPool
->getConnection( $server );
354 return array( $server, $conn );
357 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
358 return array( false, false );
365 protected function logError( $msg ) {
366 wfDebugLog( 'redis', "Redis error: $msg" );
370 * The redis extension throws an exception in response to various read, write
371 * and protocol errors. Sometimes it also closes the connection, sometimes
372 * not. The safest response for us is to explicitly destroy the connection
373 * object and let it be reopened during the next request.
374 * @param RedisConnRef $conn
375 * @param Exception $e
377 protected function handleException( RedisConnRef
$conn, $e ) {
378 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
379 $this->redisPool
->handleError( $conn, $e );
383 * Send information about a single request to the debug log
384 * @param string $method
386 * @param string $server
387 * @param bool $result
389 public function logRequest( $method, $key, $server, $result ) {
390 $this->debug( "$method $key on $server: " .
391 ( $result === false ?
"failure" : "success" ) );