redis锁 博客地址:http://www.importnew.com/27477.html 。
DistributedLock
package com.timer.common.redis;
public interface DistributedLock {
public static final long TIMEOUT_MILLIS = 10000;
public static final int RETRY_TIMES = Integer.MAX_VALUE;
public static final long SLEEP_MILLIS = 500;
public boolean lock(String key);
public boolean lock(String key, int retryTimes);
public boolean lock(String key, int retryTimes, long sleepMillis);
public boolean lock(String key, long expire);
public boolean lock(String key, long expire, int retryTimes);
public boolean lock(String key, long expire, int retryTimes, long sleepMillis);
public boolean releaseLock(String key);
}
AbstractDistributedLock
package com.timer.common.redis;
public abstract class AbstractDistributedLock implements DistributedLock {
@Override
public boolean lock(String key) {
return lock(key, TIMEOUT_MILLIS, RETRY_TIMES, SLEEP_MILLIS);
}
@Override
public boolean lock(String key, int retryTimes) {
return lock(key, TIMEOUT_MILLIS, retryTimes, SLEEP_MILLIS);
}
@Override
public boolean lock(String key, int retryTimes, long sleepMillis) {
return lock(key, TIMEOUT_MILLIS, retryTimes, sleepMillis);
}
@Override
public boolean lock(String key, long expire) {
return lock(key, expire, RETRY_TIMES, SLEEP_MILLIS);
}
@Override
public boolean lock(String key, long expire, int retryTimes) {
return lock(key, expire, retryTimes, SLEEP_MILLIS);
}
}
RedisDistributedLock
package com.timer.common.redis;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCommands;
@Slf4j
@Component
public class RedisDistributedLock extends AbstractDistributedLock {
@Resource
private RedisTemplate
例子
if (distributedLock.lock("do_approval_" + approvalUuid, 5 * 1000l, 1)) {
try {
approvalDoReturnVo = approvalService.doApprovalNewVersion(approvalUuid, approverReason, action);
distributedLock.releaseLock("do_approval_" + approvalUuid);
} catch (Exception e) {
distributedLock.releaseLock("do_approval_" + approvalUuid);
throw e;
}
}