How does YII2 use the Redis cache assistant?

//Get the key value
if (CacheHelper::get(CacheKey::rewardRedKey($params))) {
    throw new \Exception('There is a task being executed at this time');
}
CacheHelper::set(CacheKey::rewardRedKey($params), $params, 3600 * 24);
// execute your own logic
。。。。。。
// Execute successfully delete task cache
CacheHelper::del(CacheKey::rewardRedKey($params));

The base class of CacheHelper is as follows:
<?php
/**
 *How to use Redis cache assistant in YII2?
 */

namespace common\helpers;

use this;
use Yii\caching\CacheInterface;

/**
 * Redis cache helper
 * Class Cache
 * @package common\helper
 */
class CacheHelper
{
    /**
     * @param string $key
     * @return mixed
     */
    public static function has(string $key)
    {
        return self::init()->exists($key);
    }

    /**
     * @param string $key
     * @param null $default
     * @return mixed
     */
    public static function get(string $key, $default = null)
    {
        $val = self::init()->get($key);
        if (empty($val)) {
            $val = $default;
        }
        return $val;
    }

    /**
     * @param string $key
     * @param mixed $value
     * @param int|null $expire
     * @return mixed
     */
    public static function set(string $key, $value, int $expire = null)
    {
        return self::init()->set($key, $value, $expire);
    }

    /**
     * @param string $key
     * @return mixed
     */
    public static function del(string $key)
    {
        return self::init()->delete($key);
    }

    /**
     * if no write cache exists
     * @param string $key
     * @param mixed $callable
     * @param int|null $expire
     * @return mixed
     */
    public static function getOrSet(string $key, $callable, int $expire = null)
    {
        return self::init()->getOrSet($key, $callable, $expire);
    }

    /**
     * @return CacheInterface
     */
    private static function init()
    {
        return Yii::$app->cache;
    }
}

Guess you like

Origin blog.csdn.net/hechenhongbo/article/details/124913138