使用lua脚本删除redis中匹配value的key,可以避免由于方法执行时间过长而redis锁自动过期失效的时候误删其他线程的锁
public static final String UNLOCK_LUA;
static {
StringBuilder sb = new StringBuilder();
sb.append("if redis.call(\"get\",KEYS[1]) == ARGV[1] ");
sb.append("then ");
sb.append(" return redis.call(\"del\",KEYS[1]) ");
sb.append("else ");
sb.append(" return 0 ");
sb.append("end ");
UNLOCK_LUA = sb.toString();
}
public boolean setLock(String key, long expire) {
try {
RedisCallback<String> callback = (connection) -> {
JedisCommands commands = (JedisCommands) connection.getNativeConnection();
String uuid = UUID.randomUUID().toString();
return commands.set(key, uuid, "NX", "PX", expire);
};
String result = (String) redisTemplate2.execute(callback);
return !StringUtils.isEmpty(result);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
try {
RedisCallback<String> callback = (connection) -> {
JedisCommands commands = (JedisCommands) connection.getNativeConnection();
return commands.get(key);
};
String result = (String) redisTemplate2.execute(callback);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public boolean releaseLock(String key, String requestId) {
// 释放锁的时候,有可能因为持锁之后方法执行时间大于锁的有效期,此时有可能已经被另外一个线程持有锁,所以不能直接删除
try {
List<String> keys = new ArrayList<>();
keys.add(key);
List<String> args = new ArrayList<>();
args.add(requestId);
// 使用lua脚本删除redis中匹配value的key,可以避免由于方法执行时间过长而redis锁自动过期失效的时候误删其他线程的锁
// spring自带的执行脚本方法中,集群模式直接抛出不支持执行脚本的异常,所以只能拿到原redis的connection来执行脚本
RedisCallback<Long> callback = (connection) -> {
Object nativeConnection = connection.getNativeConnection();
// 集群模式和单机模式虽然执行脚本的方法一样,但是没有共同的接口,所以只能分开执行
// 集群模式
if (nativeConnection instanceof JedisCluster) {
return (Long) ((JedisCluster) nativeConnection).eval(UNLOCK_LUA, keys, args);
}
// 单机模式
else if (nativeConnection instanceof Jedis) {
return (Long) ((Jedis) nativeConnection).eval(UNLOCK_LUA, keys, args);
}
return 0L;
};
Long result = (Long) redisTemplate2.execute(callback);
return result != null && result > 0;
} catch (Exception e) {
e.printStackTrace();
} finally {
// 清除掉ThreadLocal中的数据,避免内存溢出
// lockFlag.remove();
}
return false;
}
完整代码如下:
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
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 org.springframework.stereotype.Service;
import com.google.common.collect.Maps;
import com.threeb.robot.producer.EntrustBalanceProducer;
import com.threeb.robot.rabbitMq.RabbitConfig;
import com.threeb.robot.service.ub.EntrustService;
import com.threeb.robot.utils.JsonUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisCommands;
@Component
@RabbitListener(queues = { RabbitConfig.QUEUE_PUT_1 })
@Service
public class EntrustPutReceiver {
......
......
public static final String UNLOCK_LUA;
static {
StringBuilder sb = new StringBuilder();
sb.append("if redis.call(\"get\",KEYS[1]) == ARGV[1] ");
sb.append("then ");
sb.append(" return redis.call(\"del\",KEYS[1]) ");
sb.append("else ");
sb.append(" return 0 ");
sb.append("end ");
UNLOCK_LUA = sb.toString();
}
public void updateBalance(String entrustNum, Map<String, Object> map, String id, String direction, String main_cur,
String secondary_cur, BigDecimal total, BigDecimal price, String userId) {
try {
boolean lockOk_userId_main_cur = setLock(userId + "_" + main_cur + "_lock", 10000);
boolean lockOk_userId_secondary_cur = setLock(userId + "_" + secondary_cur + "_lock", 10000);
if (lockOk_userId_main_cur && lockOk_userId_secondary_cur) {
requestId1 = get(userId + "_" + main_cur + "_lock");
requestId2 = get(userId + "_" + secondary_cur + "_lock");
//设置锁成功之后,执行相关业务逻辑
} else {
//设置锁失败,说明此锁存在,则递归调用,如果递归调用的时候设置锁成功,则会执行if逻辑。
updateBalance(entrustNum, map, id, direction, main_cur, secondary_cur, total, price, userId);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (requestId1 != null && requestId2 != null) {
releaseLock(userId + "_" + main_cur + "_lock", requestId1);
releaseLock(userId + "_" + secondary_cur + "_lock", requestId2);
}
}
}
public boolean setLock(String key, long expire) {
try {
RedisCallback<String> callback = (connection) -> {
JedisCommands commands = (JedisCommands) connection.getNativeConnection();
String uuid = UUID.randomUUID().toString();
return commands.set(key, uuid, "NX", "PX", expire);
};
String result = (String) redisTemplate2.execute(callback);
return !StringUtils.isEmpty(result);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public String get(String key) {
try {
RedisCallback<String> callback = (connection) -> {
JedisCommands commands = (JedisCommands) connection.getNativeConnection();
return commands.get(key);
};
String result = (String) redisTemplate2.execute(callback);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public boolean releaseLock(String key, String requestId) {
// 释放锁的时候,有可能因为持锁之后方法执行时间大于锁的有效期,此时有可能已经被另外一个线程持有锁,所以不能直接删除
try {
List<String> keys = new ArrayList<>();
keys.add(key);
List<String> args = new ArrayList<>();
args.add(requestId);
// 使用lua脚本删除redis中匹配value的key,可以避免由于方法执行时间过长而redis锁自动过期失效的时候误删其他线程的锁
// spring自带的执行脚本方法中,集群模式直接抛出不支持执行脚本的异常,所以只能拿到原redis的connection来执行脚本
RedisCallback<Long> callback = (connection) -> {
Object nativeConnection = connection.getNativeConnection();
// 集群模式和单机模式虽然执行脚本的方法一样,但是没有共同的接口,所以只能分开执行
// 集群模式
if (nativeConnection instanceof JedisCluster) {
return (Long) ((JedisCluster) nativeConnection).eval(UNLOCK_LUA, keys, args);
}
// 单机模式
else if (nativeConnection instanceof Jedis) {
return (Long) ((Jedis) nativeConnection).eval(UNLOCK_LUA, keys, args);
}
return 0L;
};
Long result = (Long) redisTemplate2.execute(callback);
return result != null && result > 0;
} catch (Exception e) {
e.printStackTrace();
} finally {
// 清除掉ThreadLocal中的数据,避免内存溢出
// lockFlag.remove();
}
return false;
}
}