redis分布式锁

http://doc.redisfans.com/

Redisson setNx

1.原子性:key,过期时间保证原子性,中间服务器挂了,无法释放锁(即死锁)

2.解铃还须系铃人,谁加锁,谁解锁,(锁过期,其他程序进入)

过期时间10s,业务耗时15s,A程序加锁,剩余5s内,B程序进入,释放了A程序锁。

思路:加锁时,生成一个随机数value,解锁时判断value是否与加锁时value是否一致,是,才解锁。

应用场景:定时任务

3.看门狗,watch dog,续期(锁过期,其他程序进入,同2,另外一个问题)

过期时间30s,每隔10s续更新时间为30,比如业务执行需要100s,程序执行了,10s,更新过期时间为30s

    public void run() {

	String uniqueVal = UUID.randomUUID().toString();
	String lockKey = RedisKeyHelper.syncFundAvgReturnLockKey();
	try {
	    if (redisMgr.tryLock(lockKey, uniqueVal, LOCK_EXPIRE_TIME_SEC)) {
		log.info("Get locked, so to sync avg ret");
		process();
	    }
	} catch (Exception e) {
	    log.error("Fetch fund returns exception", e);
	} finally {
	    redisMgr.releaseLock(lockKey, uniqueVal);
	}

    }
    public boolean tryLock(final String lockKey, final String randomUnValue, final int expireTime) {
        List<RedisClient> clients = this.getAliveClients(lockKey);
        return this.isAtLeastOneAvailable(clients) ? (Boolean)this.execute(new AbstractRedisCallback<Boolean>() {
            public Boolean doOperation(RedisClient client) throws Exception {
                return client.tryLock(lockKey, randomUnValue, expireTime);
            }

            public String getOptionType() {
                return "tryLock";
            }
        }, clients, lockKey, false) : false;
    }
    public boolean tryLock(String lockKey, String randomUnValue, int expireTime) {
        Jedis jedis = null;

        try {
            jedis = this.jedisPool.getResource();
            Long result = (Long)jedis.eval(LuaSecript.SETNX_AND_EXPIRE.getScript(), 1, new String[]{lockKey, randomUnValue, String.valueOf(expireTime)});
            if (result == 1L) {
                boolean var6 = true;
                return var6;
            }
        } catch (Exception var10) {
            this.logger.error("Try lock failed", var10);
        } finally {
            if (jedis != null) {
                jedis.close();
            }

        }

        return false;
    }

lua脚本: 

public enum LuaSecript {
    SETNX_AND_EXPIRE("local is_existed = redis.call('setnx', KEYS[1], ARGV[1]);if (is_existed == 1) then redis.call('expire', KEYS[1], ARGV[2]);return 1; end; return 0;"),
    DEL_KEY_AND_EQUAL_VAL("if (redis.call('get', KEYS[1]) == ARGV[1]) then return redis.call('del', KEYS[1]);else return 0;end; "),
    ZRANGEBYSCORE_ZREM("local data = redis.call('ZRANGEBYSCORE', KEYS[1], ARGV[1], ARGV[2], 'WITHSCORES', 'LIMIT', ARGV[3], ARGV[4]);if table.getn(data) > 0 then for k,v in pairs(data) do if (k % 2) ~=0 then redis.call('ZREM', KEYS[1], v);end;end;return data;end;");

    private String script;

    private LuaSecript(String script) {
        this.script = script;
    }

    public String getScript() {
        return this.script;
    }
}
if redis.call("get",KEYS[1]) == ARGV[1]
then
    return redis.call("del",KEYS[1])
else
    return 0
end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值