a9f5f8c7e2c62a644c41bed7f2299572e59fb8fb
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
22 class RedisBagOStuff
extends BagOStuff
{
23 /** @var RedisConnectionPool */
25 /** @var Array List of server names */
28 protected $automaticFailover;
31 * Construct a RedisBagOStuff object. Parameters are:
33 * - servers: An array of server names. A server name may be a hostname,
34 * a hostname/port combination or the absolute path of a UNIX socket.
35 * If a hostname is specified but no port, the standard port number
36 * 6379 will be used. Required.
38 * - connectTimeout: The timeout for new connections, in seconds. Optional,
39 * default is 1 second.
41 * - persistent: Set this to true to allow connections to persist across
42 * multiple web requests. False by default.
44 * - password: The authentication password, will be sent to Redis in
45 * clear text. Optional, if it is unspecified, no AUTH command will be
48 * - automaticFailover: If this is false, then each key will be mapped to
49 * a single server, and if that server is down, any requests for that key
50 * will fail. If this is true, a connection failure will cause the client
51 * to immediately try the next server in the list (as determined by a
52 * consistent hashing algorithm). True by default. This has the
53 * potential to create consistency issues if a server is slow enough to
54 * flap, for example if it is in swap death.
56 function __construct( $params ) {
57 $redisConf = array( 'serializer' => 'php' );
58 foreach ( array( 'connectTimeout', 'persistent', 'password' ) as $opt ) {
59 if ( isset( $params[$opt] ) ) {
60 $redisConf[$opt] = $params[$opt];
63 $this->redisPool
= RedisConnectionPool
::singleton( $redisConf );
65 $this->servers
= $params['servers'];
66 if ( isset( $params['automaticFailover'] ) ) {
67 $this->automaticFailover
= $params['automaticFailover'];
69 $this->automaticFailover
= true;
73 public function get( $key, &$casToken = null ) {
74 wfProfileIn( __METHOD__
);
75 list( $server, $conn ) = $this->getConnection( $key );
77 wfProfileOut( __METHOD__
);
81 $result = $conn->get( $key );
82 } catch ( RedisException
$e ) {
84 $this->handleException( $server, $conn, $e );
87 $this->logRequest( 'get', $key, $server, $result );
88 wfProfileOut( __METHOD__
);
92 public function set( $key, $value, $expiry = 0 ) {
93 wfProfileIn( __METHOD__
);
94 list( $server, $conn ) = $this->getConnection( $key );
96 wfProfileOut( __METHOD__
);
99 $expiry = $this->convertToRelative( $expiry );
102 // No expiry, that is very different from zero expiry in Redis
103 $result = $conn->set( $key, $value );
105 $result = $conn->setex( $key, $expiry, $value );
107 } catch ( RedisException
$e ) {
109 $this->handleException( $server, $conn, $e );
112 $this->logRequest( 'set', $key, $server, $result );
113 wfProfileOut( __METHOD__
);
117 public function cas( $casToken, $key, $value, $expiry = 0 ) {
118 wfProfileIn( __METHOD__
);
119 list( $server, $conn ) = $this->getConnection( $key );
121 wfProfileOut( __METHOD__
);
124 $expiry = $this->convertToRelative( $expiry );
126 $conn->watch( $key );
128 if ( $this->get( $key ) !== $casToken ) {
129 wfProfileOut( __METHOD__
);
136 // No expiry, that is very different from zero expiry in Redis
137 $conn->set( $key, $value );
139 $conn->setex( $key, $expiry, $value );
142 $result = $conn->exec();
143 } catch ( RedisException
$e ) {
145 $this->handleException( $server, $conn, $e );
148 $this->logRequest( 'cas', $key, $server, $result );
149 wfProfileOut( __METHOD__
);
153 public function delete( $key, $time = 0 ) {
154 wfProfileIn( __METHOD__
);
155 list( $server, $conn ) = $this->getConnection( $key );
157 wfProfileOut( __METHOD__
);
161 $conn->delete( $key );
162 // Return true even if the key didn't exist
164 } catch ( RedisException
$e ) {
166 $this->handleException( $server, $conn, $e );
168 $this->logRequest( 'delete', $key, $server, $result );
169 wfProfileOut( __METHOD__
);
173 public function getMulti( array $keys ) {
174 wfProfileIn( __METHOD__
);
177 foreach ( $keys as $key ) {
178 list( $server, $conn ) = $this->getConnection( $key );
182 $conns[$server] = $conn;
183 $batches[$server][] = $key;
186 foreach ( $batches as $server => $batchKeys ) {
187 $conn = $conns[$server];
189 $conn->multi( Redis
::PIPELINE
);
190 foreach ( $batchKeys as $key ) {
193 $batchResult = $conn->exec();
194 if ( $batchResult === false ) {
195 $this->debug( "multi request to $server failed" );
198 foreach ( $batchResult as $i => $value ) {
199 if ( $value !== false ) {
200 $result[$batchKeys[$i]] = $value;
203 } catch ( RedisException
$e ) {
204 $this->handleException( $server, $conn, $e );
208 $this->debug( "getMulti for " . count( $keys ) . " keys " .
209 "returned " . count( $result ) . " results" );
210 wfProfileOut( __METHOD__
);
214 public function add( $key, $value, $expiry = 0 ) {
215 wfProfileIn( __METHOD__
);
216 list( $server, $conn ) = $this->getConnection( $key );
218 wfProfileOut( __METHOD__
);
221 $expiry = $this->convertToRelative( $expiry );
223 $result = $conn->setnx( $key, $value );
224 if ( $result && $expiry ) {
225 $conn->expire( $key, $expiry );
227 } catch ( RedisException
$e ) {
229 $this->handleException( $server, $conn, $e );
231 $this->logRequest( 'add', $key, $server, $result );
232 wfProfileOut( __METHOD__
);
237 * Non-atomic implementation of replace(). Could perhaps be done atomically
238 * with WATCH or scripting, but this function is rarely used.
240 public function replace( $key, $value, $expiry = 0 ) {
241 wfProfileIn( __METHOD__
);
242 list( $server, $conn ) = $this->getConnection( $key );
244 wfProfileOut( __METHOD__
);
247 if ( !$conn->exists( $key ) ) {
248 wfProfileOut( __METHOD__
);
252 $expiry = $this->convertToRelative( $expiry );
255 $result = $conn->set( $key, $value );
257 $result = $conn->setex( $key, $expiry, $value );
259 } catch ( RedisException
$e ) {
261 $this->handleException( $server, $conn, $e );
264 $this->logRequest( 'replace', $key, $server, $result );
265 wfProfileOut( __METHOD__
);
270 * Non-atomic implementation of incr().
272 * Probably all callers actually want incr() to atomically initialise
273 * values to zero if they don't exist, as provided by the Redis INCR
274 * command. But we are constrained by the memcached-like interface to
275 * return null in that case. Once the key exists, further increments are
278 public function incr( $key, $value = 1 ) {
279 wfProfileIn( __METHOD__
);
280 list( $server, $conn ) = $this->getConnection( $key );
282 wfProfileOut( __METHOD__
);
285 if ( !$conn->exists( $key ) ) {
286 wfProfileOut( __METHOD__
);
290 $result = $conn->incrBy( $key, $value );
291 } catch ( RedisException
$e ) {
293 $this->handleException( $server, $conn, $e );
296 $this->logRequest( 'incr', $key, $server, $result );
297 wfProfileOut( __METHOD__
);
302 * Get a Redis object with a connection suitable for fetching the specified key
303 * @return Array (server, RedisConnRef) or (false, false)
305 protected function getConnection( $key ) {
306 if ( count( $this->servers
) === 1 ) {
307 $candidates = $this->servers
;
309 $candidates = $this->servers
;
310 ArrayUtils
::consistentHashSort( $candidates, $key, '/' );
311 if ( !$this->automaticFailover
) {
312 $candidates = array_slice( $candidates, 0, 1 );
316 foreach ( $candidates as $server ) {
317 $conn = $this->redisPool
->getConnection( $server );
319 return array( $server, $conn );
322 return array( false, false );
328 protected function logError( $msg ) {
329 wfDebugLog( 'redis', "Redis error: $msg\n" );
333 * The redis extension throws an exception in response to various read, write
334 * and protocol errors. Sometimes it also closes the connection, sometimes
335 * not. The safest response for us is to explicitly destroy the connection
336 * object and let it be reopened during the next request.
338 protected function handleException( $server, RedisConnRef
$conn, $e ) {
339 $this->redisPool
->handleException( $server, $conn, $e );
343 * Send information about a single request to the debug log
345 public function logRequest( $method, $key, $server, $result ) {
346 $this->debug( "$method $key on $server: " .
347 ( $result === false ?
"failure" : "success" ) );