YII2使用Redis缓存助手怎么使用?

//获取key值
if (CacheHelper::get(CacheKey::rewardRedKey($params))) {
    throw new \Exception('此时有任务正在执行');
}
CacheHelper::set(CacheKey::rewardRedKey($params), $params, 3600 * 24);
//执行你自己的逻辑
。。。。。。
//执行成功删除任务缓存
CacheHelper::del(CacheKey::rewardRedKey($params));

CacheHelper基类如下:
<?php
/**
 *YII2使用Redis缓存助手怎么使用?
 */

namespace common\helpers;

use Yii;
use Yii\caching\CacheInterface;

/**
 * Redis缓存助手
 * 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);
    }

    /**
     * 如果不存在写入缓存
     * @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;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值