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:-
Second request (cached):-
Also, we can monitor the Redis operation through Redis CLI.
redis-cli monitor
Be the first to comment.