Redis Queue katika Laravel: Kushughulikia Foleni

In Laravel, Redis Queue ni zana yenye nguvu inayotumika kushughulikia kazi zinazochukua muda mrefu na zinazotumia wakati bila kungoja zikamilike. Kwa kutumia Redis Queue, unaweza kuorodhesha kazi kama vile kutuma barua pepe, kuchakata kazi za usuli, au kutoa ripoti, na kuzitekeleza kwa usawa, kuboresha utendakazi wa programu na kuboresha matumizi ya mtumiaji.

Hatua za Msingi za Kutumia Redis Queue katika Laravel

Sanidi Redis

Kwanza, unahitaji kusakinisha na kusanidi Redis katika Laravel. Hakikisha umesakinisha Redis kifurushi kupitia Mtunzi na kusanidi Redis vigezo vya uunganisho kwenye .env faili.

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

Fafanua Kazi

Ifuatayo, unahitaji kufafanua kazi ambazo ungependa kuweka kwenye foleni. Kazi hizi zitafanywa asynchronously na kwa kujitegemea kwa usindikaji kuu wa programu.

// Example defining a job to send an email  
namespace App\Jobs;  
  
use Illuminate\Bus\Queueable;  
use Illuminate\Contracts\Queue\ShouldQueue;  
use Illuminate\Foundation\Bus\Dispatchable;  
use Illuminate\Queue\InteractsWithQueue;  
use Illuminate\Queue\SerializesModels;  
use Illuminate\Support\Facades\Mail;  
  
class SendEmailJob implements ShouldQueue  
{  
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;  
  
    protected $user;  
  
    public function __construct($user)  
    {  
        $this->user = $user;  
    }  
  
    public function handle()  
    {  
        // Handle sending an email to the user  
        Mail::to($this->user->email)->send(new WelcomeEmail());  
    }  
}  

Weka Ajira kwenye Foleni

Unapotaka kufanya kazi, unaiweka tu kwenye foleni kwa kutumia dispatch au dispatchNow vitendaji:

use App\Jobs\SendEmailJob;  
use Illuminate\Support\Facades\Queue;  
  
// Put the job into the queue and perform asynchronously  
Queue::push(new SendEmailJob($user));  
  
// Put the job into the queue and perform synchronously(without waiting)  
Queue::push(new SendEmailJob($user))->dispatchNow();  

Mchakato wa Kazi kutoka kwenye Foleni

Baada ya kazi kuwekwa kwenye foleni, unahitaji kusanidi Worker ili kutekeleza kazi kwenye foleni. Laravel inakuja na artisan command kuendesha worker:

php artisan queue:work

Itaendelea worker kusikiliza na kutekeleza kazi kwenye foleni. Unaweza kusanidi worker kushughulikia idadi ya kazi na muda wa kusubiri kati ya mizunguko ya usindikaji.

Dhibiti Kazi katika Foleni

Laravel hutoa kiolesura cha usimamizi ambapo unaweza kufuatilia na kudhibiti kazi kwenye foleni. Unaweza kuona idadi ya kazi ambazo hazijashughulikiwa, muda wa kuchakata, na hata kujaribu tena kazi ambazo hazijafanikiwa.

 

Hitimisho Kutumia Redis Queue ndani Laravel ni njia bora ya kushughulikia kazi za muda mrefu bila kuharibu usindikaji kuu wa programu. Kwa kutumia Redis Queue, unaweza kuboresha utendakazi wa programu na kuboresha matumizi ya mtumiaji.