代码

//行为限频
if (!function_exists('doSomethingLimit')) {
    function doSomethingLimit($key, $second, Closure $callback) {
        $reids = get_redis();
        if ($reids->SETNX($key, 1)) {  //不存在,设置成功
            $reids->EXPIRE($key, $second);
            $callback();
        }
    }
}

//套缓存
if (!function_exists('cacheRemember')) {
    function cacheRemember($key, $second, Closure $callback) {
        $redis = get_redis();

        //添加立即刷新key
        $lockKey = $key . "_flush_lock";
        $lock    = $redis->get($lockKey, 0);

        $value = $redis->get($key);
        if (!$value || $lock) {
            $value = $callback();
            if (is_array($value)) {
                $value = json_encode($value);
            }
            $redis->set($key, $value, $second);
            $redis->delete($lockKey);
        }
        return json_decode($value, true);
    }
}


//添加缓存刷新锁
if (!function_exists('flushCacheRemember')) {
    function flushCacheRemember($key) {
        $redis   = get_redis();
        $lockKey = $key . "_flush_lock";
        $lock    = $redis->set($lockKey, 1, 60);
    }
}

//添加立即刷新的用户ID
if (!function_exists('addFlushIdSet')) {
    function addFlushIdSet($userId, $sec) {
        $redis = get_redis();
        $key   = "swoft_need_flush_cache_user_id_set_" . $userId;
        $lock  = $redis->set($key, 1, $sec);
    }
}

//判断立即刷新的用户ID
if (!function_exists('checkFlushIdSet')) {
    function checkFlushIdSet($userId) {
        $redis = get_redis();
        $key   = "swoft_need_flush_cache_user_id_set_" . $userId;
        $lock  = $redis->get($key, 0);
        return $lock ? true : false;
    }
}

逻辑

  1. 添加需要立即刷新缓存的集合,默认60秒
  2. 在进入业务逻辑前添加判断,如果在集合中就表示需要立刻刷新缓存。
  3. 业务逻辑套缓存,如果是需要立即刷新的,则删除旧的直接刷新。否则走缓存逻辑。