custom/static-plugins/GlobusSW6/src/Service/Cache/HttpCacheHitMissRater.php line 37

Open in your IDE?
  1. <?php
  2. namespace GlobusSW6\Service\Cache;
  3. use Shopware\Core\Framework\Adapter\Cache\RedisConnectionFactory;
  4. use Shopware\Storefront\Framework\Cache\Event\HttpCacheHitEvent;
  5. use Shopware\Storefront\Framework\Cache\Event\HttpCacheItemWrittenEvent;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. /**
  8.  * @see https://speakerdeck.com/beberlei/best-practices-for-running-shopware-6-in-production?slide=14
  9.  */
  10. class HttpCacheHitMissRater implements EventSubscriberInterface
  11. {
  12.     private RedisConnectionFactory $redisConnectionFactory;
  13.     private string $redisDsn;
  14.     private $redis;
  15.     /**
  16.      * @param RedisConnectionFactory $redisConnectionFactory
  17.      * @param string $redisDsn
  18.      */
  19.     public function __construct(RedisConnectionFactory $redisConnectionFactorystring $redisDsn)
  20.     {
  21.         $this->redisConnectionFactory $redisConnectionFactory;
  22.         $this->redisDsn $redisDsn;
  23.     }
  24.     public static function getSubscribedEvents()
  25.     {
  26.         return [
  27.             HttpCacheItemWrittenEvent::class => 'onCacheMiss',
  28.             HttpCacheHitEvent::class => 'onCacheHit',
  29.         ];
  30.     }
  31.     public function onCacheMiss(HttpCacheItemWrittenEvent $event)
  32.     {
  33.         try {
  34.             $this->getRedis()->hIncrBy('http_cache_misses'date('YmdH'), 1);
  35.         } catch (\Throwable $t) {
  36.             // nth
  37.         }
  38.     }
  39.     public function onCacheHit(HttpCacheHitEvent $event)
  40.     {
  41.         try {
  42.             $this->getRedis()->hIncrBy('http_cache_hits'date('YmdH'), 1);
  43.         } catch (\Throwable $t) {
  44.             // nth
  45.         }
  46.     }
  47.     private function getRedis()
  48.     {
  49.         if ($this->redis === null) {
  50.             $this->redis $this->redisConnectionFactory->create($this->redisDsn);
  51.         }
  52.         return $this->redis;
  53.     }
  54. }