redisロックツールRedisLockUtils

5059 ワード

redis分布式ロックRedisLockUtilsは多くの大物が分布式ロックの実現方式を紹介する文章があって、ここで主に1つの既製のredisロックツールを記録しますhttps://www.cnblogs.com/0201zcr/p/5942748.html
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisCommands;
/**  
 * @ClassName: RedisLockUtils  
 * @Description: redis   
 * @Author:xiowewe
 *    
 */ 
@Component
public class RedisLockUtils {
    @Autowired
    private RedisTemplate redisTemplate;
 
	private static final String SET_IF_NOT_EXIST = "NX"; // key     
//	private static String SET_WITH_EXPIRE_TIME = "PX"; //   
	private static final String SET_WITH_EXPIRE_TIME = "EX"; //  
	//  lua    redis   value key
	private static final  String SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
 
	
    private final Logger logger = LoggerFactory.getLogger(RedisLockUtils.class);
 
    
	public boolean setLock(String key, String value, long expire) {
        try {
            RedisCallback callback = (connection) -> {
                JedisCommands commands = (JedisCommands) connection.getNativeConnection();
                return commands.set(key, value, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expire);
            };
            String result = redisTemplate.execute(callback);
            //      OK,   null
            return StringUtils.isNotBlank(result);
        } catch (Exception e) {
            logger.error("redis    ,key :" + key, e);
        }
        return false;
    }
 
    public String get(String key) {
        try {
            RedisCallback callback = (connection) -> {
                JedisCommands commands = (JedisCommands) connection.getNativeConnection();
                return commands.get(key);
            };
            String result = redisTemplate.execute(callback);
            return result;
        } catch (Exception e) {
            logger.error("redis     ,key :" + key, e);
        }
        return "";
    }
 
    public boolean releaseLock(String key,String value) {
        //       ,                      ,                 ,        
        try {
            List keys = new ArrayList<>();
            keys.add(key);
            List values = new ArrayList<>();
            values.add(value);
 
            //   lua    redis   value key,               redis                  
            // spring          ,                  ,       redis connection     
            RedisCallback callback = (connection) -> {
                Object nativeConnection = connection.getNativeConnection();
                //                     ,         ,        
                //     
                if (nativeConnection instanceof JedisCluster) {
                    return (Long) ((JedisCluster) nativeConnection).eval(SCRIPT, keys, values);
                }
 
                //     
                else if (nativeConnection instanceof Jedis) {
                    return (Long) ((Jedis) nativeConnection).eval(SCRIPT, keys, values);
                }
                return 0L;
            };
            Long result = redisTemplate.execute(callback);
 
            return result != null && result >= 0;
        } catch (Exception e) {
            logger.error("redis    ,key :" + key, e);
        } 
        return false;
    }
    
    public boolean releaseLockList(List keys,List values) {
    	//       ,                      ,                 ,        
    	try {
    		
    		//   lua    redis   value key,               redis                  
    		// spring          ,                  ,       redis connection     
    		RedisCallback callback = (connection) -> {
    			Object nativeConnection = connection.getNativeConnection();
    			//                     ,         ,        
    			//     
    			if (nativeConnection instanceof JedisCluster) {
    				return (Long) ((JedisCluster) nativeConnection).eval(SCRIPT, keys, values);
    			}
    			
    			//     
    			else if (nativeConnection instanceof Jedis) {
    				return (Long) ((Jedis) nativeConnection).eval(SCRIPT, keys, values);
    			}
    			return 0L;
    		};
    		Long result = redisTemplate.execute(callback);
    		
    		return result != null && result > 0;
    	} catch (Exception e) {
    		logger.error("redis    ,key :" + JSON.toJSONString(keys), e);
    	} 
    	return false;
    }

}