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.
57 function __construct( $params ) {
58 $redisConf = array( 'serializer' => 'php' );
59 foreach ( array( 'connectTimeout', 'persistent', 'password' ) as $opt ) {
60 if ( isset( $params[$opt] ) ) {
61 $redisConf[$opt] = $params[$opt];
64 $this->redisPool
= RedisConnectionPool
::singleton( $redisConf );
66 $this->servers
= $params['servers'];
67 if ( isset( $params['automaticFailover'] ) ) {
68 $this->automaticFailover
= $params['automaticFailover'];
70 $this->automaticFailover
= true;
74 public function get( $key, &$casToken = null ) {
75 wfProfileIn( __METHOD__
);
76 list( $server, $conn ) = $this->getConnection( $key );
78 wfProfileOut( __METHOD__
);
82 $result = $conn->get( $key );
83 } catch ( RedisException
$e ) {
85 $this->handleException( $server, $conn, $e );
88 $this->logRequest( 'get', $key, $server, $result );
89 wfProfileOut( __METHOD__
);
93 public function set( $key, $value, $expiry = 0 ) {
94 wfProfileIn( __METHOD__
);
95 list( $server, $conn ) = $this->getConnection( $key );
97 wfProfileOut( __METHOD__
);
100 $expiry = $this->convertToRelative( $expiry );
103 // No expiry, that is very different from zero expiry in Redis
104 $result = $conn->set( $key, $value );
106 $result = $conn->setex( $key, $expiry, $value );
108 } catch ( RedisException
$e ) {
110 $this->handleException( $server, $conn, $e );
113 $this->logRequest( 'set', $key, $server, $result );
114 wfProfileOut( __METHOD__
);
118 public function cas( $casToken, $key, $value, $expiry = 0 ) {
119 wfProfileIn( __METHOD__
);
120 list( $server, $conn ) = $this->getConnection( $key );
122 wfProfileOut( __METHOD__
);
125 $expiry = $this->convertToRelative( $expiry );
127 $conn->watch( $key );
129 if ( $this->get( $key ) !== $casToken ) {
130 wfProfileOut( __METHOD__
);
137 // No expiry, that is very different from zero expiry in Redis
138 $conn->set( $key, $value );
140 $conn->setex( $key, $expiry, $value );
144 * multi()/exec() (transactional mode) allows multiple values to
145 * be set/get at once and will return an array of results, in
146 * the order they were set/get. In this case, we only set 1
147 * value, which should (in case of success) result in true.
149 $result = ( $conn->exec() == array( true ) );
150 } catch ( RedisException
$e ) {
152 $this->handleException( $server, $conn, $e );
155 $this->logRequest( 'cas', $key, $server, $result );
156 wfProfileOut( __METHOD__
);
160 public function delete( $key, $time = 0 ) {
161 wfProfileIn( __METHOD__
);
162 list( $server, $conn ) = $this->getConnection( $key );
164 wfProfileOut( __METHOD__
);
168 $conn->delete( $key );
169 // Return true even if the key didn't exist
171 } catch ( RedisException
$e ) {
173 $this->handleException( $server, $conn, $e );
175 $this->logRequest( 'delete', $key, $server, $result );
176 wfProfileOut( __METHOD__
);
180 public function getMulti( array $keys ) {
181 wfProfileIn( __METHOD__
);
184 foreach ( $keys as $key ) {
185 list( $server, $conn ) = $this->getConnection( $key );
189 $conns[$server] = $conn;
190 $batches[$server][] = $key;
193 foreach ( $batches as $server => $batchKeys ) {
194 $conn = $conns[$server];
196 $conn->multi( Redis
::PIPELINE
);
197 foreach ( $batchKeys as $key ) {
200 $batchResult = $conn->exec();
201 if ( $batchResult === false ) {
202 $this->debug( "multi request to $server failed" );
205 foreach ( $batchResult as $i => $value ) {
206 if ( $value !== false ) {
207 $result[$batchKeys[$i]] = $value;
210 } catch ( RedisException
$e ) {
211 $this->handleException( $server, $conn, $e );
215 $this->debug( "getMulti for " . count( $keys ) . " keys " .
216 "returned " . count( $result ) . " results" );
217 wfProfileOut( __METHOD__
);
221 public function add( $key, $value, $expiry = 0 ) {
222 wfProfileIn( __METHOD__
);
223 list( $server, $conn ) = $this->getConnection( $key );
225 wfProfileOut( __METHOD__
);
228 $expiry = $this->convertToRelative( $expiry );
230 $result = $conn->setnx( $key, $value );
231 if ( $result && $expiry ) {
232 $conn->expire( $key, $expiry );
234 } catch ( RedisException
$e ) {
236 $this->handleException( $server, $conn, $e );
238 $this->logRequest( 'add', $key, $server, $result );
239 wfProfileOut( __METHOD__
);
244 * Non-atomic implementation of replace(). Could perhaps be done atomically
245 * with WATCH or scripting, but this function is rarely used.
247 public function replace( $key, $value, $expiry = 0 ) {
248 wfProfileIn( __METHOD__
);
249 list( $server, $conn ) = $this->getConnection( $key );
251 wfProfileOut( __METHOD__
);
254 if ( !$conn->exists( $key ) ) {
255 wfProfileOut( __METHOD__
);
259 $expiry = $this->convertToRelative( $expiry );
262 $result = $conn->set( $key, $value );
264 $result = $conn->setex( $key, $expiry, $value );
266 } catch ( RedisException
$e ) {
268 $this->handleException( $server, $conn, $e );
271 $this->logRequest( 'replace', $key, $server, $result );
272 wfProfileOut( __METHOD__
);
277 * Non-atomic implementation of incr().
279 * Probably all callers actually want incr() to atomically initialise
280 * values to zero if they don't exist, as provided by the Redis INCR
281 * command. But we are constrained by the memcached-like interface to
282 * return null in that case. Once the key exists, further increments are
285 public function incr( $key, $value = 1 ) {
286 wfProfileIn( __METHOD__
);
287 list( $server, $conn ) = $this->getConnection( $key );
289 wfProfileOut( __METHOD__
);
292 if ( !$conn->exists( $key ) ) {
293 wfProfileOut( __METHOD__
);
297 $result = $conn->incrBy( $key, $value );
298 } catch ( RedisException
$e ) {
300 $this->handleException( $server, $conn, $e );
303 $this->logRequest( 'incr', $key, $server, $result );
304 wfProfileOut( __METHOD__
);
309 * Get a Redis object with a connection suitable for fetching the specified key
310 * @return Array (server, RedisConnRef) or (false, false)
312 protected function getConnection( $key ) {
313 if ( count( $this->servers
) === 1 ) {
314 $candidates = $this->servers
;
316 $candidates = $this->servers
;
317 ArrayUtils
::consistentHashSort( $candidates, $key, '/' );
318 if ( !$this->automaticFailover
) {
319 $candidates = array_slice( $candidates, 0, 1 );
323 foreach ( $candidates as $server ) {
324 $conn = $this->redisPool
->getConnection( $server );
326 return array( $server, $conn );
329 return array( false, false );
335 protected function logError( $msg ) {
336 wfDebugLog( 'redis', "Redis error: $msg\n" );
340 * The redis extension throws an exception in response to various read, write
341 * and protocol errors. Sometimes it also closes the connection, sometimes
342 * not. The safest response for us is to explicitly destroy the connection
343 * object and let it be reopened during the next request.
345 protected function handleException( $server, RedisConnRef
$conn, $e ) {
346 $this->redisPool
->handleException( $server, $conn, $e );
350 * Send information about a single request to the debug log
352 public function logRequest( $method, $key, $server, $result ) {
353 $this->debug( "$method $key on $server: " .
354 ( $result === false ?
"failure" : "success" ) );