Laravel 結合 Redis 實現 PHP 定時器

xugege發表於2018-12-20

<?php
namespace App\Modules\Rtdata\Cache;
use Illuminate\Support\Facades\Redis;

class AppPushTimer
{
    protected $cache;
    protected $connection_name = 'rtdata_cache';
    protected $prefix_key = 'rtdata:%s';
    protected $ttl = 2;
    public function __construct()
    {
        if (!isset($this->cache)) {
            $this->cache = Redis::connection($this->connection_name);
        }
    }

    public function setTimer(string $type, $pair)
    {
        $key = $this->getKey($type, $pair);
        $this->cache->setex($key, $this->ttl, 1);
    }

    protected function getKey(string $type, $pair)
    {
        if (empty($pair)) {
            return sprintf($this->prefix_key, $type);
        }
        return sprintf($this->prefix_key, $type.'-'.$pair);
    }

    public function tic($type, $pair)
    {
        $is_exist = $this->getTimer($type, $pair);
        if ($is_exist) {
            return true;
        }
        $this->setTimer($type, $pair);
        return false;
    }

    protected function getTimer($type, $pair)
    {
        $key = $this->getKey($type, $pair);
        $is_exist = $this->cache->get($key);
        if (empty($is_exist)) {
            return false;
        }
        return true;
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章