简体   繁体   English

Java Spring Scheduler Lock

[英]Java Spring Scheduler Lock

I have been trying to send notifications to my customers once. 我一直试图向客户发送通知。 I'm using kubernetes and I create multiple spring boot applications because I have 2 replicas. 我正在使用kubernetes并且我创建了多个spring boot应用程序,因为我有2个副本。 This is all fine but when the scheduler runs, each one of them can send notifications. 这很好,但是当调度程序运行时,每个调度程序都可以发送通知。 I have looked a little bit at quartz but the config seems to be a little complicated. 我看了一下石英,但配置似乎有点复杂。 Is there an easy way to do so? 有一个简单的方法吗?

@Scheduled(fixedDelayString = "300000")
public void sendFlowerNotification() {
  //Code
}

You can also use dlock to execute a scheduled task only once over multiple nodes. 您还可以使用dlock仅在多个节点上执行一次计划任务。 You can simply do something like below. 您可以简单地执行以下操作。

@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);
  }
}

You can send the POD_NAME to spring as an environment variable. 您可以将POD_NAME作为环境变量发送到spring。 dlock would automatically handle it. dlock会自动处理它。

 env:
 - name: POD_NAME
   valueFrom:
     fieldRef:
       fieldPath: metadata.name

See the article about using it. 请参阅有关使用它的文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM