Redisson distributed lock integrated with @Scheduled doesn‘t guarantee a single job execution

本文探讨了如何在使用Redisson分布式锁配合Spring @Scheduled时确保单个任务的唯一执行。通过示例和建议,讨论了强制等待锁超时的重要性,并寻求其他解决方案以提高并发控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Redisson distributed lock integrated with @Scheduled doesn’t guarantee a single scheduled job execution at the same time

Here is a example below:
Thread.sleep(10000); // 如果不加改行代码,则该方法执行时间很短,比如 1ms ,那么 其他线程也是有机会重复执行的
因此,要想保证只有1个scheduled task 被执行,必须保证 在 其他线程获取锁失败,比如超时失败,或者其他的条件失败。
故:可以强制在 方法末尾 必须加上 Thread.sleep(10000);, 保证锁超时。
小伙伴们还有其他方法吗?

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = CameraApplication.class)
@Slf4j
public class RedissonTests {
    @Resource
    RedissonClient redissonClient;
    @Resource
    ExecutorService executorService;

    @Test
    public void testLock() {
        try {
            //Simulating cluster timer tasks with multiple threads
            for (int i = 1; i <= 5; i++) {
                int id = i;
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        RLock rLock = redissonClient.getLock("testLock");
                        try {
                            log.info(id + " Request Lock");
                            //Attempt to lock, wait up to 5 seconds, unlock automatically 10 seconds after lock
                            boolean lockRes = rLock.tryLock(5, 10, TimeUnit.SECONDS);
                            if (lockRes) {
                                try {
                                    log.info(id + " Application Successful,Processing business logic");
                                    Thread.sleep(10000); // 必须强制等待保证锁超时 ,那么 其他线程也就没机会重复执行了
                                } finally {
                                    //Is it locked and whether the current thread has acquired a lock
                                    if (rLock.isLocked() && rLock.isHeldByCurrentThread()) {
                                        rLock.unlock();
                                        log.info(id + " Release lock");
                                    }
                                }
                            } else {
                                log.info(id + " Failed to apply for lock=" + lockRes);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
            Thread.sleep(500000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
### 实现分布式锁的方式 在分布式环境中,为了确保多个进程不会同时访问共享资源,通常会采用分布式锁机制。一种常见的方法是在ZooKeeper这样的协调服务上创建临时顺序节点来实现锁定功能[^4]。 当客户端希望获取锁时,它会在特定路径下创建一个带有`EPHEMERAL_SEQUENTIAL`标志的节点。由于这些节点按照创建时间有序编号,因此可以通过比较当前节点与其他兄弟节点的名字前缀判断自己是否获得了锁。如果发现自己是最小的那个,则意味着成功取得了互斥权;否则就监听比自己稍早一点建立起来的那个节点的状态变化事件并等待其消失后再重新评估是否有资格成为新的最小者从而获得锁。 除了基于ZooKeeper外,还有其他几种流行的方案用于构建可靠的分布式锁: - **Redisson**: 使用Redis作为存储后端提供了一套简单易用API接口封装好的RedLock算法实现; - **Chubby**: Google开发的服务发现工具同时也支持简单的文件系统操作以及读写权限控制等功能,在内部实现了较为复杂的选举协议保障安全性; - **Etcd**: CoreOS团队出品的支持多版本并发控制(MVCC)特性的键值数据库同样适用于搭建高可用集群环境下的全局同步原语。 无论选用哪种技术栈去部署实际项目中的分布式锁组件,都需要注意以下几点最佳实践原则以保证系统的稳定性和性能表现最优: - 尽量缩短持有锁的时间长度减少竞争冲突概率; - 设置合理的超时期限防止死锁发生; - 对异常情况进行充分测试验证恢复能力; - 考虑到网络分区场景设计容错策略。 ```java // Java示例代码展示如何利用Curator框架配合Apache Zookeeper快速搭建起一套基本版Distributed Locks应用逻辑 import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.locks.InterProcessMutex; public class DistributedLockExample { private static final String LOCK_PATH = "/distributed-lock"; public void acquireLock(CuratorFramework client) throws Exception { InterProcessMutex lock = new InterProcessMutex(client, LOCK_PATH); try { lock.acquire(); System.out.println("Lock acquired."); // Critical section code here... } finally { if (lock.isAcquiredInThisProcess()) { lock.release(); System.out.println("Lock released."); } } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值