猿问

Java Spring 调度程序锁

我一直在尝试向我的客户发送通知。我正在使用 kubernetes 并且我创建了多个 Spring Boot 应用程序,因为我有 2 个副本。这一切都很好,但是当调度程序运行时,他们每个人都可以发送通知。我看过一点点石英,但配置似乎有点复杂。有没有简单的方法来做到这一点?


@Scheduled(fixedDelayString = "300000")

public void sendFlowerNotification() {

  //Code

}


繁华开满天机
浏览 151回答 1
1回答

犯罪嫌疑人X

您还可以使用dlock在多个节点上仅执行一次计划任务。您可以简单地执行以下操作。@Scheduled(fixedDelayString = "300000")@TryLock(name = "flowerNotification", owner = POD_NAME, lockFor = THREE_MINUTES)public void sendFlowerNotifications() {&nbsp; List<Notification> notifications = notificationService.getNotifications();&nbsp; for(Notification notification: notifications){&nbsp; &nbsp; sendNotification(notification);&nbsp; }}您可以将 POD_NAME 作为环境变量发送到 spring。dlock 会自动处理它。&nbsp;env:&nbsp;- name: POD_NAME&nbsp; &nbsp;valueFrom:&nbsp; &nbsp; &nbsp;fieldRef:&nbsp; &nbsp; &nbsp; &nbsp;fieldPath: metadata.name请参阅有关使用它的文章。
随时随地看视频慕课网APP

相关分类

Java
我要回答