Installation
composer require allprogrammic/redis-client
Register the service provider in config/app.php:
'providers' => [
Allprogrammic\RedisClient\RedisServiceProvider::class,
],
Basic Configuration Publish the config file:
php artisan vendor:publish --provider="Allprogrammic\RedisClient\RedisServiceProvider" --tag="config"
Edit config/redis-client.php to match your Redis server details (host, port, password, etc.).
First Use Case: Simple Connection Inject the Redis client into a controller or service:
use Allprogrammic\RedisClient\Facades\RedisClient;
public function testRedis()
{
$redis = RedisClient::connection();
$redis->set('key', 'value');
$value = $redis->get('key');
return $value; // Returns 'value'
}
Connection Management
Use named connections for different environments (e.g., redis:cache, redis:session):
$redis = RedisClient::connection('redis:cache');
Pub/Sub Integration Publish messages:
RedisClient::connection()->publish('channel', 'message');
Subscribe in a separate process (e.g., queue worker):
RedisClient::connection()->subscribe(['channel'], function ($message) {
// Handle message
});
Pipeline Operations Batch commands for efficiency:
$redis = RedisClient::connection();
$redis->pipeline(function ($pipe) {
$pipe->set('key1', 'value1');
$pipe->set('key2', 'value2');
$pipe->incr('counter');
});
Laravel Integration Use with Laravel’s cache system for Redis-backed storage:
Cache::store('redis')->put('key', 'value', $seconds);
Transactions Execute atomic operations:
$redis = RedisClient::connection();
$redis->multi()
->set('a', 1)
->incr('b')
->exec();
Connection Timeouts
'timeout' => 5.0, // seconds
retry() for transient failures:
RedisClient::connection()->retry(3, function () {
$redis->get('key');
});
Blocking Commands
BRPOPLPUSH or BLPOP block execution. Run in background processes (e.g., queues) or use non-blocking alternatives.Serialization Issues
Redis::rawCommand() for complex cases:
Redis::rawCommand('HSET user:1 name "John" age 30');
Memory Leaks
RedisClient::connection()->unsubscribe();
RedisClient::connection()->flushDb(); // Use cautiously!
Enable Logging
Add to config/redis-client.php:
'log' => [
'enabled' => true,
'channel' => 'single',
],
Check logs for connection issues or command failures.
Check Redis CLI Verify keys/data directly:
redis-cli KEYS *
redis-cli GET my_key
Custom Commands Extend the client with raw Redis commands:
RedisClient::connection()->rawCommand('EVAL', $luaScript, 1, 'key');
Middleware Add middleware for auth or rate limiting:
RedisClient::connection()->middleware(function ($command) {
if ($command === 'DEL') {
// Custom logic
}
});
Event Listeners
Listen for Redis events (e.g., key expiry) via Redis::on() if the package supports it (check docs for custom events).
Testing
Use Redis::fake() (if supported) or mock the connection:
$this->mock(RedisClient::class)->shouldReceive('get')->andReturn('mocked_value');
How can I help you explore Laravel packages today?