How can use Redis Client cache on afterGetList function in Magento 2

23 views Asked by At

I have created plugin for afterGetList() to added extension attribute data in searchCriteria. But I want to add searchCriteria in cache, How can we implement this? I if searchCriteria parameter change then redis cache searchCriteria will be update and return same searchCriteria.

I was trying this way -


    public function afterGetList(
        \Magento\Catalog\Api\ProductRepositoryInterface $subject,
        \Magento\Catalog\Api\Data\ProductSearchResultsInterface $searchCriteria
    ) : \Magento\Catalog\Api\Data\ProductSearchResultsInterface
    {
        $customerId = $this->request->getParam('cust_id');

        
        $cacheKey = 'your_custom_cache_key_' . md5($this->jsonSerializer->serialize($this->request->getParams()));

        // Check if data is in the cache
        $cachedData = $this->cache->load($cacheKey);

        if ($cachedData) {
            // If data is found in the cache, decode JSON and return it
            $unserializedData = json_decode($cachedData, true);

            if (is_array($unserializedData) && isset($unserializedData['items'])) {
                // Reconstruct ProductSearchResultsInterface with unserialized data
                $searchCriteria = $this->jsonSerializer->unserialize(json_encode($unserializedData));
                return $searchCriteria;
            }
        }
       
        $products = [];
        foreach ($searchCriteria->getItems() as $entity) {
            $product = $entity;
            
            $products[] = $product;
        }
        
        $searchCriteria->setItems($products);

        // Serialize and save the data to the cache
        $this->cache->save(
            json_encode($searchCriteria),
            $cacheKey,
            ['your_custom_cache_tag'],
            3600 // Cache lifetime in seconds
        );

       
        return $searchCriteria;
    }
0

There are 0 answers