我一直在尝试向我的客户发送通知。我正在使用 kubernetes 并且我创建了多个 spring boot 应用程序,因为我有 2 个副本。这一切都很好,但是当调度程序运行时,它们中的每一个都可以发送通知。我看过一点 quartz ,但配置似乎有点复杂。有没有简单的方法来做到这一点?
@Scheduled(fixedDelayString = "300000")
public void sendFlowerNotification() {
//Code
}
最佳答案
您还可以使用 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);
}
}
您可以将 POD_NAME 作为环境变量发送到 spring。 dlock 会自动处理它。
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
参见 article关于使用它。
关于Java Spring 调度器锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53024514/