RedisCache.php 5.93 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\caching;

10
use yii\redis\Connection;
11 12

/**
13
 * RedisCache implements a cache application component based on [redis](http://redis.io/) version 2.6.12 or higher.
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
 *
 * RedisCache needs to be configured with [[hostname]], [[port]] and [[database]] of the server
 * to connect to. By default RedisCache assumes there is a redis server running on localhost at
 * port 6379 and uses the database number 0.
 *
 * RedisCache also supports [the AUTH command](http://redis.io/commands/auth) of redis.
 * When the server needs authentication, you can set the [[password]] property to
 * authenticate with the server after connect.
 *
 * See [[Cache]] manual for common cache operations that RedisCache supports.
 * Unlike the [[CCache]], RedisCache allows the expire parameter of
 * [[set]] and [[add]] to be a floating point number, so you may specify the time in milliseconds.
 *
 * To use RedisCache as the cache application component, configure the application as follows,
 *
 * ~~~
Alexander Makarov committed
30 31 32 33 34 35 36 37 38 39
 * [
 *     'components' => [
 *         'cache' => [
 *             'class' => 'RedisCache',
 *             'hostname' => 'localhost',
 *             'port' => 6379,
 *             'database' => 0,
 *         ],
 *     ],
 * ]
40 41
 * ~~~
 *
42
 * @property Connection $connection The redis connection object. This property is read-only.
43
 *
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
class RedisCache extends Cache
{
	/**
	 * @var string hostname to use for connecting to the redis server. Defaults to 'localhost'.
	 */
	public $hostname = 'localhost';
	/**
	 * @var int the port to use for connecting to the redis server. Default port is 6379.
	 */
	public $port = 6379;
	/**
	 * @var string the password to use to authenticate with the redis server. If not set, no AUTH command will be sent.
	 */
	public $password;
	/**
	 * @var int the redis database to use. This is an integer value starting from 0. Defaults to 0.
	 */
	public $database = 0;
	/**
	 * @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")
	 */
	public $connectionTimeout = null;
	/**
	 * @var float timeout to use for redis socket when reading and writing data. If not set the php default value will be used.
	 */
	public $dataTimeout = null;
	/**
74
	 * @var Connection the redis connection
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
	 */
	private $_connection;


	/**
	 * Initializes the cache component by establishing a connection to the redis server.
	 */
	public function init()
	{
		parent::init();
		$this->getConnection();
	}

	/**
	 * Returns the redis connection object.
	 * Establishes a connection to the redis server if it does not already exists.
91
	 * @return Connection the redis connection object.
92 93 94 95
	 */
	public function getConnection()
	{
		if ($this->_connection === null) {
Alexander Makarov committed
96
			$this->_connection = new Connection([
97 98 99 100
				'dsn' => 'redis://' . $this->hostname . ':' . $this->port . '/' . $this->database,
				'password' => $this->password,
				'connectionTimeout' => $this->connectionTimeout,
				'dataTimeout' => $this->dataTimeout,
Alexander Makarov committed
101
			]);
102 103 104 105
		}
		return $this->_connection;
	}

106 107 108 109 110 111 112 113 114 115 116 117
	/**
	 * Checks whether a specified key exists in the cache.
	 * This can be faster than getting the value from the cache if the data is big.
	 * Note that this method does not check whether the dependency associated
	 * with the cached data, if there is any, has changed. So a call to [[get]]
	 * may return false while exists returns true.
	 * @param mixed $key a key identifying the cached value. This can be a simple string or
	 * a complex data structure consisting of factors representing the key.
	 * @return boolean true if a value exists in cache, false if the value is not in the cache or expired.
	 */
	public function exists($key)
	{
Alexander Makarov committed
118
		return (bool) $this->_connection->executeCommand('EXISTS', [$this->buildKey($key)]);
119 120
	}

121
	/**
122
	 * @inheritDocs
123 124 125
	 */
	protected function getValue($key)
	{
Alexander Makarov committed
126
		return $this->_connection->executeCommand('GET', [$key]);
127 128 129
	}

	/**
130
	 * @inheritDocs
131 132 133 134
	 */
	protected function getValues($keys)
	{
		$response = $this->_connection->executeCommand('MGET', $keys);
Alexander Makarov committed
135
		$result = [];
136
		$i = 0;
137
		foreach ($keys as $key) {
138 139 140 141 142 143
			$result[$key] = $response[$i++];
		}
		return $result;
	}

	/**
144
	 * @inheritDocs
145
	 */
146
	protected function setValue($key, $value, $expire)
147 148
	{
		if ($expire == 0) {
Alexander Makarov committed
149
			return (bool) $this->_connection->executeCommand('SET', [$key, $value]);
150 151
		} else {
			$expire = (int) ($expire * 1000);
152
			return (bool) $this->_connection->executeCommand('SET', [$key, $value, 'PX', $expire]);
153 154 155 156
		}
	}

	/**
157
	 * @inheritDocs
158
	 */
159
	protected function setValues($data, $expire)
160
	{
161 162 163 164 165 166 167
		$args = [];
		foreach($data as $key => $value) {
			$args[] = $key;
			$args[] = $value;
		}

		$failedKeys = [];
168
		if ($expire == 0) {
169
			$this->_connection->executeCommand('MSET', $args);
170 171 172
		} else {
			$expire = (int) ($expire * 1000);
			$this->_connection->executeCommand('MULTI');
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
			$this->_connection->executeCommand('MSET', $args);
			$index = [];
			foreach ($data as $key => $value) {
				$this->_connection->executeCommand('PEXPIRE', [$key, $expire]);
				$index[] = $key;
			}
			$result = $this->_connection->executeCommand('EXEC');
			array_shift($result);
			foreach($result as $i => $r) {
				if ($r != 1) {
					$failedKeys[] = $index[$i];
				}
			}
		}
		return $failedKeys;
	}

	/**
	 * @inheritDocs
	 */
	protected function addValue($key, $value, $expire)
	{
		if ($expire == 0) {
			return (bool) $this->_connection->executeCommand('SET', [$key, $value, 'NX']);
		} else {
			$expire = (int) ($expire * 1000);
			return (bool) $this->_connection->executeCommand('SET', [$key, $value, 'PX', $expire, 'NX']);
200 201 202 203
		}
	}

	/**
204
	 * @inheritDocs
205 206 207
	 */
	protected function deleteValue($key)
	{
Alexander Makarov committed
208
		return (bool) $this->_connection->executeCommand('DEL', [$key]);
209 210 211
	}

	/**
212
	 * @inheritDocs
213 214 215 216 217 218
	 */
	protected function flushValues()
	{
		return $this->_connection->executeCommand('FLUSHDB');
	}
}