Skip to content

Instantly share code, notes, and snippets.

@jbardnz
Created September 12, 2017 02:28
Show Gist options
  • Save jbardnz/75fe228ebbb1a8fac6c14d8ca8a1e49d to your computer and use it in GitHub Desktop.
Save jbardnz/75fe228ebbb1a8fac6c14d8ca8a1e49d to your computer and use it in GitHub Desktop.
Monitor Redis and restart queues if master changes.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;
use Predis\Client;
class MonitorRedisMaster extends Command
{
protected $signature = 'redis:monitor-master';
protected $description = 'Monitors redis for a change in master and restarts the queues';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$redis_hosts = config('database.redis.default');
$current_master = Cache::store('file')->get('current_redis_master', null);
$this->info('Current master: ' . $current_master);
//Remove the options key
unset($redis_hosts['options']);
foreach($redis_hosts as $redis_host){
$host_ip = $redis_host['host'];
$client = new Client('tcp://' . $host_ip .':6379');
$status = $client->info('Replication');
$role = $status['Replication']['role'];
$this->info('Checking host: ' . $host_ip);
$this->info('Status: ' . $role);
if($role == 'master' && $host_ip != $current_master && $current_master != null){
//Master changed
$this->warn('Result: master has changed - restarting queues');
//Set master
Cache::store('file')->forever('current_redis_master', $host_ip);
//Restart queues
Artisan::call('queue:restart');
}else{
//set master again
Cache::store('file')->forever('current_redis_master', $host_ip);
$this->info('Result: master has not changed');
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment