yiisoft/yii2-redis
Yii2 Redis extension providing a Redis connection plus Cache, Session, and Mutex handlers, and a Redis-backed ActiveRecord for storing and querying structured data. Requires Redis 2.6.12+ and PHP 7.4+ (best on PHP 8).
Installation:
composer require yiisoft/yii2-redis
Add the extension to your config/web.php or config/console.php:
'components' => [
'redis' => [
'class' => 'yiisoft\redis\Connection',
'hostname' => '127.0.0.1',
'port' => 6379,
'database' => 0,
],
],
First Use Case:
Yii::$app->redis->set('key', 'value');
$value = Yii::$app->redis->get('key');
session component to use Redis:
'components' => [
'session' => [
'class' => 'yii\web\Session',
'cookieMode' => 'none',
'savePath' => Yii::$app->redis,
],
],
Documentation:
Yii::$app->redis->setex('temp_key', 3600, 'data'); // Expires in 1 hour
Yii::$app->redis->del('key'); // Manual invalidation
Yii::$app->redis->expire('key', 0); // Force expiration
Yii::$app->session->set('user_id', 123);
$userId = Yii::$app->session->get('user_id');
config/web.php:
'session' => [
'timeout' => 1800, // 30 minutes
],
$model = User::findOne(1);
Yii::$app->redis->set('user:1', serialize($model), 3600); // Cache for 1 hour
Yii::$app->redis->set('user:1', serialize($model), 3600);
Yii::$app->redis->sadd('user:tags', 'user:1'); // Add to tag set
Yii::$app->redis->delByTag('user:tags'); // Invalidate all tagged keys
yiisoft/yii2-queue).$key = 'rate_limit:user:' . $userId;
if (Yii::$app->redis->incr($key) > 100) {
throw new \yii\web\TooManyRequestsHttpException();
}
Yii::$app->redis->expire($key, 60); // Reset after 60 seconds
Yii::$app->redis->publish('channel', 'message');
Yii::$app->redis->subscribe(['channel'], function ($message) {
// Handle message
});
redis-cli ping).try {
Yii::$app->redis->connect();
} catch (\RedisException $e) {
Yii::$app->errorHandler->logException($e);
// Fallback to file cache or throw an error
}
Yii::$app->redis->set('key', json_encode($data));
$data = json_decode(Yii::$app->redis->get('key'), true);
redis-cli info memory). Use maxmemory-policy in Redis config to avoid evictions.redis-cli to inspect keys:
redis-cli keys * # List all keys (use cautiously in production)
redis-cli get key
redis-cli ttl key
config/web.php:
'redis' => [
'class' => 'yiisoft\redis\Connection',
'log' => true, // Enable logging
],
RedisException: Check connection settings and Redis server status.InvalidArgumentException: Ensure keys are strings and values are serializable.'components' => [
'redisCache' => [
'class' => 'yiisoft\redis\Cache',
'redis' => ['hostname' => '127.0.0.1', 'port' => 6379],
],
'redisSession' => [
'class' => 'yiisoft\redis\Session',
'redis' => ['hostname' => '127.0.0.1', 'port' => 6380],
],
],
password to Redis config if required:
'redis' => [
'password' => 'your_password',
],
class CustomRedis extends \yiisoft\redis\Connection {
public function hsetnx($key, $field, $value) {
return $this->executeCommand('HSETNX', [$key, $field, $value]);
}
}
Then bind it in config:
'redis' => ['class' => 'app\components\CustomRedis'],
Yii::$app->redis->subscribe(['events'], function ($message) {
Yii::$app->trigger('event', new \yii\base\Event(['data' => $message]));
});
Predis or phpredis with a custom connection class:
'redis' => [
'class' => 'Predis\Client',
'parameters' => [
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379,
'cluster' => 'redis',
],
],
How can I help you explore Laravel packages today?