John Davidson

php - Laravel: Redis cache in background issue

0 comments
Message:


I have a schedule task which runs every 5 minutes.


This schedule command puts some data to Redis cache via controller.


Kernel.php


...
protected $commands = [
Commands\DataCommand::class,
];

protected function schedule(Schedule $schedule)
{
$schedule->command('data:cache')->everyFiveMinutes()->onOneServer()->runInBackground();
}

DataCommand.php


...
public function handle()
{
app('App\Http\Controllers\DataProcessing')->setCache();
}

DataProcessing.php


...
public function setCache()
{
$data = ['one', 'two', 'three'];
Cache::store('redis')->put('data', $data, now()->addMinutes(10));
}

This doesn't work with runInBackground. When I am trying to get data from the cache it returns null anyway.


So, when I remove ->runInBackground() it works perfectly and then I can get data from Redis cache as expected.


The problem that it executes sequentially in foreground but I want to run all schedule tasks simultaneously in background.


Why I can't access cache when task is running in background and how to overcome this issue?



My Answer:
>command('data:cache')->everyFiveMinutes();
}

However, when running this schedule task, I noticed that the Redis cache operation is blocking the background process and causing delays in other tasks. How can I resolve this issue and ensure that the Redis cache operation runs in the background without affecting other tasks?

One way to resolve this issue is to use Laravel's queue system to handle the Redis cache operation in the background. You can create a new job class that performs the Redis cache operation and dispatch this job from your controller instead of directly performing the operation.

Here's an example of how you can create a job class for the Redis cache operation:

php
php artisan make:job CacheDataJob


In the `CacheDataJob` class, you can implement the logic for the Redis cache operation:

php
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;

class CacheDataJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

public function __construct()
{
//
}

public function handle()
{
// Perform the Redis cache operation here
}
}


Then, in your controller, you can dispatch the `CacheDataJob` instead of directly performing the Redis cache operation:

php
use App\Jobs\CacheDataJob;

public function cacheData()
{
CacheDataJob::dispatch();
}


By using Laravel's queue system, the Redis cache operation will be handled in the background by the queue worker, allowing your schedule task to continue running without delays.

Rate this post

3 of 5 based on 6284 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us