Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

防缓存失效惊群 #303

Open
guanhui07 opened this issue Mar 21, 2019 · 0 comments
Open

防缓存失效惊群 #303

guanhui07 opened this issue Mar 21, 2019 · 0 comments

Comments

@guanhui07
Copy link
Owner

guanhui07 commented Mar 21, 2019

大并发下 防缓存失效惊群

public function setByLock($key, $value, $ttl = null,$redis)
    {
        if (is_numeric($ttl) && intval($ttl) > 0) {
            $ttl = intval($ttl);
            $exp = time() + $ttl;
            $arg = array("data" => $value, "expire" => $exp);
        } else {
            $ttl = 30;//300
            $exp = time() + $ttl;
        }
        empty($ttl) OR $ttl += 30; //300增加redis缓存时间,使程序有足够的时间生成缓存
        $arg = array("data" => $value, "expire" => $exp);
        $rs = $redis->setex($key, $ttl, json_encode($arg, TRUE));
        $redis->del($key . ".lock");
        return $rs;
    }   

    public function getByLock($key,$redis)
    {
        $sth = $redis->get($key);
        if ($sth === false) {
            return $sth;
        } else {
            $sth = json_decode($sth, TRUE);
            if (intval($sth['expire']) <= time()) {
                $lock = $redis->incr($key . ".lock");
                if ($lock === 1) {
                    return false;
                } else {
                    return $sth['data'];
                }
            } else {
                return $sth['data'];
            }
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant