Real-time Sanarwa tare Laravel da kuma Redis

Real-time sanarwa abu ne na gama gari a cikin aikace-aikacen yanar gizo don samar da faɗakarwa da sabuntawa ga masu amfani ba tare da buƙatar sabunta shafin ba. A cikin Laravel, zaku iya haɗawa cikin sauƙi Redis don aiwatar da real-time sanarwar da inganci. Redis za a yi amfani da shi azaman jerin gwano don isar da sanarwa daga uwar garken ga abokin ciniki nan take.

Shigarwa Redis da Laravel

Don farawa, shigar Redis a kan uwar garken ku kuma shigar da predis/predis kunshin Laravel ta hanyar Mawaki.

composer require predis/predis

Real-time Haɗin Fadakarwa

Sanya jerin gwano a ciki Laravel

Da farko, saita jerin gwano Laravel ta hanyar ƙara Redis bayanin zuwa .env fayil ɗin.

QUEUE_CONNECTION=redis  
REDIS_HOST=127.0.0.1  
REDIS_PASSWORD=null  
REDIS_PORT=6379  

Ƙirƙiri wani Event

Ƙirƙiri event shiga Laravel don aika real-time sanarwa.

php artisan make:event NewNotificationEvent

Sa'an nan, bude app/Events/NewNotificationEvent.php fayil kuma siffanta event abun ciki.

use Illuminate\Broadcasting\Channel;  
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;  
use Illuminate\Queue\SerializesModels;  
  
class NewNotificationEvent implements ShouldBroadcastNow  
{  
    use SerializesModels;  
  
    public $message;  
  
    public function __construct($message)  
    {  
        $this->message = $message;  
    }  
  
    public function broadcastOn()  
    {  
        return new Channel('notifications');  
    }  
}  

Sanya Broadcast Driver

Buɗe config/broadcasting.php fayil ɗin kuma yi amfani da redis direba don aiwatar da real-time sanarwa tare da Redis.

'connections' => [  
    'redis' => [  
        'driver' => 'redis',  
        'connection' => 'default',  
    ],  
    // ...  
],  

Aika Real-time Sanarwa

Lokacin da kake buƙatar aika real-time sanarwa, yi amfani da abin da event ka ƙirƙira a cikin mai sarrafawa ko mai bada sabis.

use App\Events\NewNotificationEvent;  
  
public function sendNotification()  
{  
    $message = 'You have a new notification!';  
    event(new NewNotificationEvent($message));  
}  

Sarrafa Real-time Sanarwa akan Abokin ciniki

A ƙarshe, sarrafa real-time sanarwar akan abokin ciniki ta amfani da JavaScript da Laravel Echo. Tabbatar cewa kun shigar kuma kun saita Laravel Echo don aikace-aikacenku.

// Connect to the 'notifications' channel  
const channel = Echo.channel('notifications');  
  
// Handle the event when receiving a real-time notification  
channel.listen('.NewNotificationEvent',(notification) => {  
    alert(notification.message);  
});  

 

Kammalawa

Haɗin kai Redis da Laravel ba ku damar tura real-time sanarwar cikin sauƙi a cikin aikace-aikacen gidan yanar gizon ku. Lokacin da aka sami sabon sanarwa, aikace-aikacen zai aika ta hanyar Redis, kuma abokin ciniki zai karɓi sanarwar nan take ba tare da buƙatar sabunta shafin ba. Wannan yana haɓaka ƙwarewar mai amfani kuma yana haɓaka hulɗar aikace-aikacen.