」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何為 Laravel API 建立緩存層

如何為 Laravel API 建立緩存層

發佈於2024-11-04
瀏覽:317

Let's say you are building an API to serve some data, you discover GET responses are quite slow. You have tried optimizing your queries, indexing your database tables by frequently queried columns and you are still not getting the response times you want. The next step to take is to write a Caching layer for your API. 'Caching layer' here is just a fancy term for a middleware that stores successful responses in a fast to retrieve store. e.g. Redis, Memcached etc. then any further requests to the API checks if the data is available in the store and serves the response.

Prerequisites

  • Laravel
  • Redis

Before we start

I am assuming if you have gotten here, you know how to create a laravel app. You should also have either a local or cloud Redis instance to connect to. If you have docker locally, you can copy my compose file here. Also, for a guide on how to connect to the Redis cache driver read here.

Creating our Dummy Data

To help us see our caching layer is working as expected. of course we need some data let's say we have a model named Post. so I will be creating some posts, I will also add some complex filtering that could be database intensive and then we can optimize by caching.

Now let's start writing our middleware:

We create our middleware skeleton by running

php artisan make:middleware CacheLayer

Then register it in your app/Http/Kernel.php under the api middleware group like so:

    protected $middlewareGroups = [
        'api' => [
            CacheLayer::class,
        ],
    ];

But if you are running Laravel 11. register it in your bootstrap/app.php

->withMiddleware(function (Middleware $middleware) {
        $middleware->api(append: [
            \App\Http\Middleware\CacheLayer::class,
        ]);
    })

Caching Terminologies

  • Cache Hit: occurs when data requested is found in the cache.
  • Cache Miss: happens when the requested data is not found in the cache.
  • Cache Flush: clearing out the stored data in the cache so that it can be repopulated with fresh data.
  • Cache tags: This is a feature unique to Redis. cache tags are a feature used to group related items in the cache, making it easier to manage and invalidate related data simultaneously.
  • Time to Live (TTL): this refers to the amount of time a cached object stays valid before it expires. One common misunderstanding is thinking that every time an object is accessed from the cache (a cache hit), its expiry time gets reset. However, this isn't true. For instance, if the TTL is set to 5 minutes, the cached object will expire after 5 minutes, no matter how many times it's accessed within that period. After the 5 minutes are up, the next request for that object will result in a new entry being created in the cache.

Computing a Unique Cache Key

So cache drivers are a key-value store. so you have a key then the value is your json. So you need a unique cache key to identify resources, a unique cache key will also help in cache invalidation i.e. removing cache items when a new resource is created/updated. My approach for cache key generation is to turn the request url, query params, and body into an object. then serialize it to string. Add this to your cache middleware:

class CacheLayer 
{
    public function handle(Request $request, Closure $next): Response
    {
    }

    private function getCacheKey(Request $request): string
    {
        $routeParameters = ! empty($request->route()->parameters) ? $request->route()->parameters : [auth()->user()->id];
        $allParameters = array_merge($request->all(), $routeParameters);
        $this->recursiveSort($allParameters);

        return $request->url() . json_encode($allParameters);
    }

    private function recursiveSort(&$array): void
    {
        foreach ($array as &$value) {
            if (is_array($value)) {
                $this->recursiveSort($value);
            }
        }

        ksort($array);
    }
}

Let's go through the code line by line.

  • First we check for the matched request parameters. we don't want to compute the same cache key for /users/1/posts and /users/2/posts.
  • And if there are no matched parameters we pass in the user's id. This part is optional. If you have routes like /user that returns details for the currently authenticated user. it will be suitable to pass in the user id in the cache key. if not you can just make it an empty array([]).
  • Then we get all the query parameters and merge it with the request parameters
  • Then we sort the parameters, why this sorting step is very important is so we can return same data for let's say /posts?page=1&limit=20 and /posts?limit=20&page=1. so regardless of the order of the parameters we still return the same cache key.

Excluding routes

So depending on the nature of the application you are building. There will be some GET routes that you don't want to cache so for this we create a constant with the regex to match those routes. This will look like:

 private const EXCLUDED_URLS = [
    '~^api/v1/posts/[0-9a-zA-Z] /comments(\?.*)?$~i'
'
];

In this case, this regex will match all a post's comments.

Configuring TTL

For this, just add this entry to your config/cache.php

  'ttl' => now()->addMinutes(5),

Writing our Middleware

Now we have all our preliminary steps set we can write our middleware code:

public function handle(Request $request, Closure $next): Response
    {
        if ('GET' !== $method) {
           return $next($request);
        }

        foreach (self::EXCLUDED_URLS as $pattern) {
            if (preg_match($pattern, $request->getRequestUri())) {
                return $next($request);
            }
        }

        $cacheKey = $this->getCacheKey($request);

        $exception = null;

        $response = cache()
            ->tags([$request->url()])
            ->remember(
                key: $cacheKey,
                ttl: config('cache.ttl'),
                callback: function () use ($next, $request, &$exception) {
                    $res = $next($request);

                    if (property_exists($res, 'exception') && null !== $res->exception) {
                        $exception = $res;

                        return null;
                    }

                    return $res;
                }
            );

        return $exception ?? $response;
    }
  • First we skip caching for non-GET requests and Excluded urls.
  • Then we use the cache helper, tag that cache entry by the request url.
  • we use the remember method to store that cache entry. then we call the other handlers down the stack by doing $next($request). we check for exceptions. and then either return the exception or response.

Cache Invalidation

When new resources are created/updated, we have to clear the cache, so users can see new data. and to do this we will tweak our middleware code a bit. so in the part where we check the request method we add this:

if ('GET' !== $method) {
    $response = $next($request);

    if ($response->isSuccessful()) {
        $tag = $request->url();

        if ('PATCH' === $method || 'DELETE' === $method) {
            $tag = mb_substr($tag, 0, mb_strrpos($tag, '/'));
        }

        cache()->tags([$tag])->flush();
    }

    return $response;
}

So what this code is doing is flushing the cache for non-GET requests. Then for PATCH and Delete requests we are stripping the {id}. so for example if the request url is PATCH /users/1/posts/2 . We are stripping the last id leaving /users/1/posts. this way when we update a post, we clear the cache of all a users posts. so the user can see fresh data.

Now with this we are done with the CacheLayer implementation. Lets test it

Testing our Cache

Let's say we want to retrieve all a users posts, that has links, media and sort it by likes and recently created. the url for that kind of request according to the json:api spec will look like: /posts?filter[links]=1&filter[media]=1&sort=-created_at,-likes. on a posts table of 1.2 million records the response time is: ~800ms

How to build a caching layer for your Laravel API
and after adding our cache middleware we get a response time of 41ms

How to build a caching layer for your Laravel API

Great success!

Optimizations

Another optional step is to compress the json payload we store on redis. JSON is not the most memory-efficient format, so what we can do is use zlib compression to compress the json before storing and decompress before sending to the client.
the code for that will look like:

$response = cache()
            ->tags([$request->url()])
            ->remember(
                key: $cacheKey,
                ttl: config('cache.ttl'),
                callback: function () use ($next, $request, &$exception) {
                    $res = $next($request);

                    if (property_exists($res, 'exception') && null !== $res->exception) {
                        $exception = $res;

                        return null;
                    }

                    return gzcompress($res->getContent());
                }
            );

        return $exception ?? response(gzuncompress($response));

The full code for this looks like:

getMethod();

        if ('GET' !== $method) {
            $response = $next($request);

            if ($response->isSuccessful()) {
                $tag = $request->url();

                if ('PATCH' === $method || 'DELETE' === $method) {
                    $tag = mb_substr($tag, 0, mb_strrpos($tag, '/'));
                }

                cache()->tags([$tag])->flush();
            }

            return $response;
        }

        foreach (self::EXCLUDED_URLS as $pattern) {
            if (preg_match($pattern, $request->getRequestUri())) {
                return $next($request);
            }
        }

        $cacheKey = $this->getCacheKey($request);

        $exception = null;

        $response = cache()
            ->tags([$request->url()])
            ->remember(
                key: $cacheKey,
                ttl: config('cache.ttl'),
                callback: function () use ($next, $request, &$exception) {
                    $res = $next($request);

                    if (property_exists($res, 'exception') && null !== $res->exception) {
                        $exception = $res;

                        return null;
                    }

                    return gzcompress($res->getContent());
                }
            );

        return $exception ?? response(gzuncompress($response));
    }

    private function getCacheKey(Request $request): string
    {
        $routeParameters = ! empty($request->route()->parameters) ? $request->route()->parameters : [auth()->user()->id];
        $allParameters = array_merge($request->all(), $routeParameters);
        $this->recursiveSort($allParameters);

        return $request->url() . json_encode($allParameters);
    }

    private function recursiveSort(&$array): void
    {
        foreach ($array as &$value) {
            if (is_array($value)) {
                $this->recursiveSort($value);
            }
        }

        ksort($array);
    }
}

Summary

This is all I have for you today on caching, Happy building and drop any questions, commments and improvements in the comments!

版本聲明 本文轉載於:https://dev.to/nelwhix/how-to-build-a-caching-layer-for-your-laravel-api-1265?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 如何在 Golang Web 伺服器中串流 MP4 影片?
    如何在 Golang Web 伺服器中串流 MP4 影片?
    GoLang Web 伺服器串流影片GoLang Web 伺服器串流影片GoLang Web 伺服器串流影片問:Golang Web 伺服器設定為服務HTML、CSS、JavaScript 和映像失敗嘗試串流式傳輸MP4 視訊。 if contentType == "video/mp4&q...
    程式設計 發佈於2024-11-14
  • Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta:列偏移的刪除和恢復Bootstrap 4 在其Beta 1 版本中引入了重大更改柱子偏移了。然而,隨著 Beta 2 的後續發布,這些變化已經逆轉。 從 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    程式設計 發佈於2024-11-14
  • CSS 中的「display: table-column」實際上做了什麼?
    CSS 中的「display: table-column」實際上做了什麼?
    CSS「display: table-column」該如何運作? 在 HTML 中,表格由行組成,每行含有細胞。 CSS 擴展了這個概念,讓設計者定義特定的行和列佈局。雖然「display: table-row」和「display: table-cell」很簡單,但「display: table-c...
    程式設計 發佈於2024-11-14
  • Babel 6 如何以不同的方式處理預設導出?
    Babel 6 如何以不同的方式處理預設導出?
    重大變更:Babel 6 匯出預設行為隨著 Babel 6 的發布,預設導出的處理方式發生了重大變化。雖然 Babel 之前新增了 module.exports = Exports["default"] 行,但此功能已被刪除。 此修改需要更改模組導入語法。以前,使用舊語法的程式碼...
    程式設計 發佈於2024-11-14
  • 掌握 Next.js 中的 SSR:如何提升 SEO 與使用者體驗
    掌握 Next.js 中的 SSR:如何提升 SEO 與使用者體驗
    SSR(伺服器端渲染)是 Next.js 中產生頁面的另一種方法。在本文中,我想解釋什麼是 SSR、它是如何運作的,以及如何在 Next.js 專案的 Page Router 和 App Router 中實現它。 什麼是SSR? SSR是一種在使用者發出請求後產生靜態頁面(或預先渲...
    程式設計 發佈於2024-11-14
  • 為什麼 PHP 5.2 不允許抽象靜態類別方法?
    為什麼 PHP 5.2 不允許抽象靜態類別方法?
    PHP 5.2 嚴格模式:為什麼不允許抽象靜態類別方法? 在 PHP 5.2 中,啟用嚴格警告可能會觸發熟悉的警告:「靜態函數不應該是抽象的」。此警告源自於 PHP 5.2 中引入的一項更改,該更改不允許抽象靜態類別方法。 原因:歷史監督PHP 5.2 最初缺乏後期靜態綁定,使抽象靜態函數變得無用。...
    程式設計 發佈於2024-11-14
  • 如何為 10 個連續點的每段繪製不同顏色的線?
    如何為 10 個連續點的每段繪製不同顏色的線?
    用不同的顏色繪製一條線問題陳述給定兩個列表,latt和lont,目標是繪製一條線,其中每個清單10個連續點的線段以不同的顏色表示。 解決方案解決方案線段數量有限import numpy as np import matplotlib.pyplot as plt # Generate random c...
    程式設計 發佈於2024-11-14
  • 如何在 MySQL 中根據計數過濾資料而不使用嵌套 SELECT?
    如何在 MySQL 中根據計數過濾資料而不使用嵌套 SELECT?
    MySQL - 在WHERE 子句中使用COUNT(*)使用者在嘗試使用WHERE 子句中的COUNT(*) 函數過濾MySQL 中的資料時遇到了挑戰WHERE 子句。他們尋求一種有效的方法來完成此任務,而不使用巢狀 SELECT 語句,因為它會消耗大量資源。 使用者提供了以下偽代碼來說明他們期望的...
    程式設計 發佈於2024-11-14
  • 如何在 Python 中按名稱存取 SQL 結果列值?
    如何在 Python 中按名稱存取 SQL 結果列值?
    在Python 中按列名稱存取SQL 結果列值處理資料庫中的大量列時,依賴列索引資料來擷取可能會變得很麻煩。本文透過提供一種在 Python 中使用列名稱檢索 SQL 結果列值的方法來解決對更直觀方法的需求。 解決方案:利用 DictCursor Python 的 MySQLdb 模組提供了 Dic...
    程式設計 發佈於2024-11-14
  • 何時使用 Django ORM 的 select_lated 與 prefetch_lated?
    何時使用 Django ORM 的 select_lated 與 prefetch_lated?
    Django ORM 的 select_lated 和 prefetch_lated 之間的區別在 Django ORM 中,select_lated 和 prefetch_lated 方法在管理資料庫查詢中的關係方面具有不同的用途。 select_latedDjango的select_lated方...
    程式設計 發佈於2024-11-14
  • 大批
    大批
    方法是可以在物件上呼叫的 fns 數組是對象,因此它們在 JS 中也有方法。 slice(begin):將陣列的一部分提取到新數組中,而不改變原始數組。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index ...
    程式設計 發佈於2024-11-14
  • 在 Go 中使用 WebSocket 進行即時通信
    在 Go 中使用 WebSocket 進行即時通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    程式設計 發佈於2024-11-13
  • 如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    在 PHP 中組合關聯數組在 PHP 中,將兩個關聯數組組合成一個數組是常見任務。考慮以下請求:問題描述:提供的代碼定義了兩個關聯數組,$array1和$array2。目標是建立一個新陣列 $array3,它合併兩個陣列中的所有鍵值對。 此外,提供的陣列具有唯一的 ID,而名稱可能重疊。要求是建構一...
    程式設計 發佈於2024-11-13
  • 使用 Python 將 .png 檔案從一個資料夾移到另一個資料夾
    使用 Python 將 .png 檔案從一個資料夾移到另一個資料夾
    嘗試之前;請確保您的電腦上安裝了 python。 在 python IDE 中,您需要先匯入 pathlib 和 os 函式庫。兩者都是 python 標準函式庫的一部分,因此不需要外部安裝。 1.)導入必要的函式庫(pathlib和os)。 2.)找到桌面的路徑。 3.) 建立一個名為「S...
    程式設計 發佈於2024-11-13
  • Node.js 流:什麼、為什麼以及如何使用它們
    Node.js 流:什麼、為什麼以及如何使用它們
    高效处理大数据对于现代 Web 应用程序至关重要。将整个文件加载到内存中的传统方法对于处理大量数据来说并不是最佳选择。这就是 Node.js 中的 Streams 派上用场的地方。它们允许您逐段(以块的形式)处理数据,从而提高性能、减少内存使用并提高效率。在本文中,我们将探讨什么是流、为什么它们很重...
    程式設計 發佈於2024-11-13

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3