redis实现分布式锁的用法

1.redis锁

import java.util.Collections;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;

@Slf4j
@Component
public class DistributionLock {

   private static final String LOCK_SUCCESS = "OK";
   private static final String SET_IF_NOT_EXIST = "NX";
   private static final String SET_WITH_EXPIRE_TIME = "PX";
   
    private static final Long RELEASE_SUCCESS = 1L;

    @Autowired
    private   CacheKit cacheKit;
    
   /**
    * 尝试获取分布式锁
    * 
    * @param jedis
    *            Redis客户端
    * @param lockKey
    *            锁
    * @param requestId
    *            请求标识
    * @param expireTime
    *            超期时间
    * @return 是否获取成功
    */
   public  boolean tryGetDistributedLock(String lockKey, String requestId, int expireTime) {
       
       Jedis jedis = cacheKit.getJedis();

      String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
      cacheKit.returnResource(jedis);
      
      if (LOCK_SUCCESS.equals(result)) {
            return true;
      }
      return false;

   }


    /**
     * 释放分布式锁
     * @param jedis Redis客户端
     * @param lockKey      * @param requestId 请求标识
     * @return 是否释放成功
     */
    public  boolean releaseDistributedLock(String lockKey, String requestId) {
       Jedis jedis = cacheKit.getJedis();
       
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
        
        cacheKit.returnResource(jedis);
        
        if (RELEASE_SUCCESS.equals(result)) {
            return true;
        }
        return false;

    }

}
注入
@Autowired
private DistributionLock distributionLock;
//定时任务
boolean tryGetDistributedLock = distributionLock.tryGetDistributedLock(lockKey,requestId,31536000);

if(

tryGetDistributedLock 

){

执行任务的代码

}


猜你喜欢

转载自blog.csdn.net/heihei_100/article/details/80704088