Cope with high concurrency scenarios lock technique redis

// Get the lock
a GETLOCK () {
    // whether any threads are executing
    boolean hasLock = false;
    the try {
        hasLock = redisClient.setnx ( "lockKey", "ING") == 1;
        IF (hasLock) {
            redisClient.expire ( "lockKey", 60 * 60) ; // one hour
        }
    } the catch (Exception E) {
        logger.error ( "IS redis.lock.setnx error", E);
        // to avoid lock is acquired successfully, but does not successfully set expiration time
        redisClient.expire ( "lockKey", 60 * 60); // one hour
    }
    
    reutrn hasLock;
}

// release lock
RELEASELOCK () {
    redisClient.del ( "lockKey");
}

// call entry
doMethod () {
    if (!a GETLOCK ()) {
        // did not get to lock
        return "not allowed to call";
    }

    // get the lock, start processing
    the try {
        // service logic execution

        return "process is successful";
    } the finally {
        // just acquired lock, after the end of the business logic, the lock must be released
        RELEASELOCK ();
    }

    return "exception ";
}

 

redisClient.setnx, the setting value to a timestamp, a job may then be required to check whether the timing to release the lock, or to add a step prior getLock operation, get ( "lockKey") to the time stamp check whether release the lock, and del ( "lockkey")

Guess you like

Origin www.cnblogs.com/zhuyeshen/p/10979943.html