Skip to content

Instantly share code, notes, and snippets.

@vuthaihoc
Created November 26, 2020 10:29
Show Gist options
  • Save vuthaihoc/8ea833663b5aa884c5df7cdc1c145f77 to your computer and use it in GitHub Desktop.
Save vuthaihoc/8ea833663b5aa884c5df7cdc1c145f77 to your computer and use it in GitHub Desktop.
demo redis pub/sub
<?php
declare(ticks = 1);
namespace App\Console\Commands;
use Illuminate\Console\Command;
class ChatCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'chat {channel : Pub/sub channel} {my_name : Your name}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Chat app';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$channel = $this->argument('channel');
$my_name = $this->argument('my_name');
if($my_name == 'screen'){
return $this->messageScreen($channel);
}
$redis_connection = "pub_sub";
$this->info( "Connecting channel : " . $channel);
try{
\Redis::connection($redis_connection)->publish( $channel, $my_name . " joined.");
$this->info( "Connected " . $channel);
}catch (\Exception $ex){
$this->error( get_class($ex) . "::Can not subscribe channel " . $channel);
}
pcntl_signal(SIGINT, function ($signo) {
echo "CATCH!\n";
exit;
});
while (1){
$msg = $this->ask( "Your message : (type exit/quit to quit)");
dump($msg);
if (in_array( $msg, ["exit","quit"])){
exit();
}
\Redis::connection($redis_connection)->publish( $channel, $my_name . " : " . $msg);
}
}
public function showMessage($payload, $channel){
dump($payload);
}
protected function messageScreen($channel){
$redis_connection = "pub_sub";
$this->info( "Screen :: " . $channel);
while(1){
try{
\Redis::connection($redis_connection)->subscribe( $channel, function ($payload, $channel){
return $this->showMessage($payload, $channel);
});
}catch (\Exception $ex){
}
}
}
public function __destruct() {
\Redis::connection("pub_sub")->publish( "home", "Ai do" . " left.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment