Java Spring 调度程序锁

avi*_*ild 5 java spring scheduler quartz-scheduler

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

@Scheduled(fixedDelayString = "300000")
public void sendFlowerNotification() {
  //Code
}
Run Code Online (Sandbox Code Playgroud)

Wil*_*hes 5

您还可以使用dlock在多个节点上仅执行一次计划任务。您可以简单地执行以下操作。

@Scheduled(fixedDelayString = "300000")
@TryLock(name = "flowerNotification", owner = POD_NAME, lockFor = THREE_MINUTES)
public void sendFlowerNotifications() {
  List<Notification> notifications = notificationService.getNotifications();
  for(Notification notification: notifications){
    sendNotification(notification);
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以将 POD_NAME 作为环境变量发送到 spring。dlock 会自动处理它。

 env:
 - name: POD_NAME
   valueFrom:
     fieldRef:
       fieldPath: metadata.name
Run Code Online (Sandbox Code Playgroud)

请参阅有关使用它的文章

  • 这就像一个魅力。非常感谢 POD_NAME 环境配置。我会浪费大量时间来弄清楚如何传递 pod 名称。 (2认同)