Back to Top

How to use Redis cache for Magento 2 API response.

Updated 29 November 2023

Redis is an in-memory database popularly used as a cache.

To proceed with caching API response you have to install and configure Redis cache in Magento 2.

Here we have created a REST Magento 2 API with sample data in response.

<?php

namespace Webkul\ApiService\Model;

class ApiManagement implements \Webkul\ApiService\Api\ApiManagementInterface
{
    public function __construct(
        \Magento\Framework\App\CacheInterface $cache
    ) {
        $this->cache = $cache;
    }
    /**
     * get test Api data.
     *
     * @api
     *
     * @return \Webkul\ApiService\Api\Data\ApiInterface
     */
    public function getApiData()
    {
        $cacheData = $this->cache->load('22_test_identifier');
        if ($cacheData) {
            return json_decode($cacheData, true);
        }
        $returnArray = [];
        $returnArray[] = [
            'id' => 22,
            'name' => "Test",
            'description' => "test description"
        ];
        $this->cache->save(json_encode($returnArray),"22_test_identifier", ["test_api_cache_tag"], 82000);
        sleep(2);
        return $returnArray;
    }
}

In the above API model, we are saving the response in the cache and get the cached data on top with the help of the cache identifier. We have added a sleep function to differentiate the response timings.

Now we can check by making a request to the API. First request:-

Searching for an experienced
Magento 2 Company ?
Find out More
initial_hit

Second request (cached):-

cached_hit

Also, we can monitor the Redis operation through Redis CLI.

redis-cli monitor
redis cache monitor

Magento 2 cache management.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home