package com.xu.redis.task;
import cn.hutool.core.date.DateUtil;
import lombok.extern.log4j.Log4j2;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* @author xuyq
*/
@Log4j2
@Component
@EnableScheduling
public class TestTask {
@Resource
private RedissonClient client;
private final static String LOCKS = "DISTRIBUTED_LOCKS";
@Scheduled(cron = "0/10 * * * * ?")
public void test() {
RLock lock = client.getLock(LOCKS);
try {
// 尝试1秒内获取锁,如果获取到了,最长60秒自动释放
boolean tryLock = lock.tryLock(1L, 60L, TimeUnit.SECONDS);
if (tryLock) {
// TODO: 获取锁成功,处理业务
System.out.println("获取锁成功" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
}
} catch (Exception e) {
log.error("加锁异常!", e);
} finally {
if (lock.isLocked() && lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
}
文章来源地址https://www.toymoban.com/news/detail-545506.html
文章来源:https://www.toymoban.com/news/detail-545506.html
到了这里,关于RedissonClient 分布式锁的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!