>  기사  >  백엔드 개발  >  Laravel API용 캐싱 레이어를 구축하는 방법

Laravel API용 캐싱 레이어를 구축하는 방법

PHPz
PHPz원래의
2024-08-10 06:59:32830검색

일부 데이터를 제공하기 위해 API를 구축하고 있다고 가정해 보겠습니다. GET 응답이 매우 느리다는 것을 알게 됩니다. 쿼리 최적화를 시도하고 자주 쿼리되는 열을 기준으로 데이터베이스 테이블을 인덱싱했지만 여전히 원하는 응답 시간을 얻지 못하고 있습니다. 다음 단계는 API용 캐싱 레이어를 작성하는 것입니다. 여기서 '캐싱 레이어'는 성공적인 응답을 빠르게 검색할 수 있는 저장소에 저장하는 미들웨어에 대한 멋진 용어일 뿐입니다. 예를 들어 Redis, Memcached 등이 API에 대한 추가 요청이 있으면 스토어에서 데이터를 사용할 수 있는지 확인하고 응답을 제공합니다.

전제 조건

  • 라라벨
  • 레디스

시작하기 전에

여기까지 오셨다면 laravel 앱을 만드는 방법을 아실 것이라고 가정합니다. 또한 연결할 로컬 또는 클라우드 Redis 인스턴스가 있어야 합니다. 로컬에 Docker가 있는 경우 여기에 작성 파일을 복사할 수 있습니다. 또한 Redis 캐시 드라이버에 연결하는 방법에 대한 안내는 여기에서 읽어보세요.

더미 데이터 생성

캐싱 계층이 예상대로 작동하는지 확인하는 데 도움이 됩니다. 물론 데이터가 필요합니다. Post라는 모델이 있다고 가정해 보겠습니다. 그래서 몇 가지 게시물을 작성하고 데이터베이스 집약적일 수 있는 복잡한 필터링도 추가한 다음 캐싱을 통해 최적화할 것입니다.

이제 미들웨어 작성을 시작해 보겠습니다.

다음을 실행하여 미들웨어 뼈대를 만듭니다

php artisan make:middleware CacheLayer

그런 다음 api 미들웨어 그룹 아래 app/Http/Kernel.php에 다음과 같이 등록하세요.

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

그러나 Laravel 11을 실행하고 있다면 bootstrap/app.php에 등록하세요

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

캐싱 용어

  • 캐시 히트: 요청한 데이터가 캐시에서 발견될 때 발생합니다.
  • 캐시 미스: 요청한 데이터가 캐시에 없을 때 발생합니다.
  • 캐시 플러시: 새로운 데이터로 다시 채울 수 있도록 캐시에 저장된 데이터를 지웁니다.
  • 캐시 태그: 이는 Redis의 고유한 기능입니다. 캐시 태그는 캐시에 있는 관련 항목을 그룹화하는 기능으로, 관련 데이터를 동시에 관리하기 쉽고 무효화하는 기능을 제공합니다.
  • TTL(Time to Live): 캐시된 객체가 만료되기 전에 유효한 상태로 유지되는 시간을 나타냅니다. 일반적인 오해 중 하나는 캐시에서 객체에 액세스할 때마다(캐시 적중) 만료 시간이 재설정된다고 생각하는 것입니다. 그러나 이는 사실이 아닙니다. 예를 들어 TTL이 5분으로 설정된 경우 캐시된 객체는 해당 기간 내에 액세스한 횟수에 관계없이 5분 후에 만료됩니다. 5분이 지나면 해당 개체에 대한 다음 요청으로 인해 캐시에 새 항목이 생성됩니다.

고유한 캐시 키 계산

그래서 캐시 드라이버는 키-값 저장소입니다. 따라서 키가 있으면 값은 json입니다. 따라서 리소스를 식별하려면 고유한 캐시 키가 필요합니다. 고유한 캐시 키는 캐시 무효화(예: 새 리소스가 생성/업데이트될 때 캐시 항목 제거)에도 도움이 됩니다. 캐시 키 생성에 대한 나의 접근 방식은 요청 URL, 쿼리 매개변수 및 본문을 개체로 바꾸는 것입니다. 그런 다음 문자열로 직렬화하십시오. 캐시 미들웨어에 다음을 추가하세요:

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);
    }
}

코드를 한 줄씩 살펴보겠습니다.

  • 먼저 일치하는 요청 매개변수를 확인합니다. /users/1/posts와 /users/2/posts에 대해 동일한 캐시 키를 계산하고 싶지 않습니다.
  • 일치하는 매개변수가 없으면 사용자 ID를 전달합니다. 이 부분은 선택사항입니다. 현재 인증된 사용자에 대한 세부 정보를 반환하는 /user와 같은 경로가 있는 경우. 캐시 키에 사용자 ID를 전달하는 것이 적합합니다. 그렇지 않다면 그냥 빈 배열([])로 만들 수 있습니다.
  • 그런 다음 모든 쿼리 매개변수를 가져와 요청 매개변수와 병합합니다
  • 그런 다음 매개변수를 정렬합니다. 이 정렬 단계가 매우 중요한 이유는 /posts?page=1&limit=20 및 /posts?limit=20&page=1에 대해 동일한 데이터를 반환할 수 있기 때문입니다. 따라서 매개변수의 순서에 관계없이 여전히 동일한 캐시 키를 반환합니다.

노선 제외

따라서 구축 중인 애플리케이션의 성격에 따라 달라집니다. 캐시하고 싶지 않은 일부 GET 경로가 있으므로 이를 위해 해당 경로와 일치하는 정규식을 사용하여 상수를 만듭니다. 다음과 같습니다.

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

이 경우 이 정규식은 모든 게시물의 댓글과 일치합니다.

TTL 구성

이를 위해서는 이 항목을 config/cache.php에 추가하세요

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

미들웨어 작성

이제 미들웨어 코드를 작성할 수 있는 모든 예비 단계가 설정되었습니다.

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!

위 내용은 Laravel API용 캐싱 레이어를 구축하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.