Petro Gromovo
Petro Gromovo

Reputation: 2173

Why \Cache::remember and Cache::put do not write data into redis?

Checking which methods can be used with writing data in redis(it is supposed that item data would be often read and not often writte) I found that \Cache::remember and Cache::put do not work at all !

<?php

namespace App\Jobs;

use App\Library\Services\Interfaces\LogInterface;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Models\Item;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;


/*
php artisan job:dispatchNow ItemsCachingJob
*/

class ItemsCachingJob
{
    // Interface for logging messages
    protected $logger;
    use Dispatchable;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->logger = app(LogInterface::class);
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        ...
        $ret = \Cache::remember($redisUniqueKey.'aaa', $itemsCachingHours, function() use($item) {
            return serialize( $item->toArray());
        });
        \Log::info($ret); // I see no data in redis, but I see packed string in log file

        $ret2 = Cache::put($redisUniqueKey.'bbb', serialize( $item->toArray()), $itemsCachingHours);
        \Log::info($ret2);  // I see no data in redis, but I see boolean value "1" in log file

        $ret3 = Redis::set($redisUniqueKey, serialize( $item->toArray()));
        \Log::info($ret3); // I SEE Valid data in redis with valid key and valid TTL, and I see array => Array   (
        [ Predis\Response\Status payload] => OK)

        Redis::expire($redisUniqueKey, $itemsCachingHours);

I used

use Illuminate\Support\Facades\Cache;

Is it correct file to import ?

Why so ?

"laravel/framework": "^9.47", 
"predis/predis": "^2.1",

    
    

Thanks in advance!

Upvotes: 0

Views: 819

Answers (1)

KennetsuR
KennetsuR

Reputation: 788

  1. please check config in .env file
        CACHE_DRIVER=redis
  1. for writing data into redis, you can use below code
        Cache::set('barcx', 'bazs', 600); // 10 Minutes

OR

        Cache::store('redis')->put('bar', 'baz', 600); // 10 Minutes
  1. please check the right db(db0,db1...) in redis. In my trying, cache operation would like to write into db1, but normal redis operation would like to write into db0.

Upvotes: 0

Related Questions