dimanche 28 octobre 2018

Laravel Caching with Redis is very slow

I´m making my first steps with Redis on Laravel and there is something odd I figured out.

When using Redis as a cache driver in my setup it is taking far way to much time to load a page.

How do I know? When not using the Cache facade but the Redis facade directly response times are just a fraction. I set up a laravel installation on scratch and build a migration and seeder for a simple Article model.

First I thought the items were not stored in redis as redis-cli didn´t show them when searching with KEYS *. I figured out the cache is stored in another DB with REDIS_CACHE_DB as found in config/database.php `INFO keyspace in redis-cli lists those two DB´s named 0 and 1.

I thought the problem could be caused by my localhost setup with Mamp Pro. So I switched over to the Laravel Homestead box and uploaded my project there. Same here.

Here´s the code I´m using: routes/web.php

use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use App\Article;

Route::get('/get-articles-mysql', function (Request $request) {
    return response()->json(Article::take(20000)->get());
});


Route::get('/get-articles-cache', function (Request $request) {
    return Cache::remember('posts', 60, function () {
        return Article::take(20000)->get();
    });

});

Route::get('/get-articles-redis', function (Request $request) {
    if($posts = Redis::get('posts.all')) {
        return response()->json(json_decode($posts));
    }

    $posts = Article::take(20000)->get();
    Redis::set('posts.all', Article::take(20000)->get());
    return response()->json($posts);

});

I´m using postman to get the response times. I made several runs as the caching routes should be slow on the first request when caching is empty. But what I get on the average is this:

http://laravel-echo.local/get-articles-mysql 583ms
http://laravel-echo.local/get-articles-redis 62ms
http://laravel-echo.local/get-articles-cache 730ms

I´m not getting this. Using the Redis facade directly is super-fast. But why is caching so slow? Yes, I double checked my .env files. There is CACHE_DRIVER=redis so I´m not using file system by accident. And I used both php artisan config:clear and php artisan cache:clear to avoid mistakes when debugging.

I see a key called "laravel_cache:posts" in redis-cli. The cached posts are there. It only takes ages to load them. I also tested the requests in Chrome. The response times are much longer but still caching takes more than mere mysql querying.

So any suggestions what could be going on here?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire