Real-time Arifa na Laravel na Redis

Real-time arifa ni kipengele cha kawaida katika programu za wavuti kutoa arifa na masasisho ya papo hapo kwa watumiaji bila hitaji la kuonyesha upya ukurasa. Katika Laravel, unaweza kuunganisha kwa urahisi Redis ili kutekeleza real-time arifa kwa ufanisi. Redis itatumika kama foleni ya kuwasilisha arifa kutoka kwa seva hadi kwa mteja papo hapo.

Kufunga Redis na Laravel

Ili kuanza, sakinisha Redis kwenye seva yako na usakinishe predis/predis kifurushi Laravel kupitia Mtunzi.

composer require predis/predis

Kuunganisha Real-time Arifa

Sanidi Foleni ndani Laravel

Kwanza, sanidi foleni Laravel kwa kuongeza Redis habari kwenye .env faili.

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

Unda Event

Unda event ili Laravel utume real-time arifa.

php artisan make:event NewNotificationEvent

Kisha, fungua app/Events/NewNotificationEvent.php faili na ubinafsishe event yaliyomo.

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');  
    }  
}  

Sanidi Broadcast Driver

Fungua config/broadcasting.php faili na utumie redis dereva kutekeleza real-time arifa na Redis.

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

Tuma Real-time Arifa

Unapohitaji kutuma real-time arifa, tumia event uliyounda kwenye kidhibiti au mtoa huduma.

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

Shughulikia Real-time Arifa kwa Mteja

Hatimaye, shughulikia real-time arifa kwa mteja kwa kutumia JavaScript na Laravel Echo. Hakikisha umesakinisha na kusanidi Laravel Echo kwa programu yako.

// 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);  
});  

 

Hitimisho

Kuunganisha Redis na Laravel kukuruhusu kupeleka real-time arifa kwa urahisi katika programu yako ya wavuti. Wakati kuna arifa mpya, programu itaituma kupitia Redis, na mteja atapokea arifa hiyo papo hapo bila hitaji la kuonyesha upya ukurasa. Hii inaboresha matumizi ya mtumiaji na huongeza mwingiliano wa programu.