redis 简单分布式锁dome
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
@Component
public class DistrbutedLockUtil {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Value("${server.port}")
private String port;
public boolean lock(String key, long timeout, TimeUnit unit) throws UnknownHostException {
String ip = InetAddress.getLocalHost().getHostAddress() + ":" + port;
return stringRedisTemplate.opsForValue().setIfAbsent(key, ip, timeout, unit);
}
public void unlock(String key) {
if ("".equals(key)) {
System.out.println("没有锁,不需要锁释锁!");
} else {
String str = stringRedisTemplate.delete(key) == true ? "锁释放成功" : "锁释放失败";
System.out.println(key + str);
}
}
}
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Component
public class DomeTask1 {
@Autowired
private DistrbutedLockUtil distrbutedLockUtil;
@Scheduled(cron = "0 */1 * * * ?")
public void dome() throws Exception {
String key = "dome";
try {
Boolean flagLock = distrbutedLockUtil.lock(key,30,TimeUnit.SECONDS);
if (!flagLock) {
key = "";
System.out.println("-----抢redis锁失败-----");
} else {
System.out.println("-----抢redis锁成功-----");
Date now2 = Calendar.getInstance().getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(format1.format(now2) + " 在这里执行定时任务的业务.....");
Thread.sleep(20000);
System.out.println("-----业务执行完成-----");
}
} finally {
distrbutedLockUtil.unlock(key);
}
}
}