lua脚本做redis的锁

package com.wosai.upay.job.biz;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Arrays;


public class RedisLock {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final static DefaultRedisScript LOCK_LUA_SCRIPT = new DefaultRedisScript<>(
            "if redis.call('setnx',KEYS[1],ARGV[1]) == 1 then return redis.call('expire',KEYS[1],ARGV[2])  else return 0 end"
            , Long.class
    );

    private final static DefaultRedisScript UNLOCK_LUA_SCRIPT = new DefaultRedisScript<>(
            "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end"
            , Long.class
    );

    
    public boolean lock(final String key, final String value, long timeInSeconds) {
        Long result = redisTemplate.execute(LOCK_LUA_SCRIPT, Arrays.asList(key), value, String.valueOf(timeInSeconds));
        return result == 1;
    }


    public boolean unlock(String key, String value) {
        Long result = redisTemplate.execute(UNLOCK_LUA_SCRIPT, Arrays.asList(key), value);
        return result != null && result == 1;
    }
}
 if (!redisLock.lock(key, value,”时间“)) {
            return;
        }
        try {
           //做业务
        } catch (Exception e) {
//业务处理
        } finally {
            redisLock.unlock(key, value);
        }

参考:https://blog.csdn.net/lmx125254/article/details/89604638

你可能感兴趣的:(redis)