Webkul
Services
Technologies Bagisto QloApps
iOS Android SAP BigCommerce Wix
Trusted by
Samsung Intel Toyota Walmart Disney Nokia Nestlé Decathlon
See all customers
Back to Top
DEV

How to use Redis cache for Magento 2 API response.

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 requesting the API. First request:-

initial_hit

Second request (cached):-

cached_hit

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

redis-cli monitor
redis cache monitor

You can also check the Tips and Tricks of Caching in Magento 2

If you require technical support, feel free to email us at [email protected].

Discover a variety of solutions to enhance your store’s functionality by exploring the Magento 2 modules section.

For personalized features or expert guidance, consider hiring, hire Magento 2 Developers for your project.

. . .

Leave a Comment

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


3 comments

  • ram
    • Kartik Upadhyay (Moderator)
      • ram
  • Back to Top

    Message Sent!

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

    Back to Home