在java springboot中的两个副本集中运行调度的重复

问题描述 投票:0回答:1

我的服务有两个副本集在 kubernetes 环境上运行。我面临的问题是我有一个将在凌晨 1 点运行的计划,它会发送一些通知。但是当两个副本都运行时,它会向用户发送重复的通知。

@Scheduled(cron = "0 0 1 * * *")
public void agentExpirationAlertForAGENT_ALERT_1() throws JsonProcessingException {
    ConfigurationModel config = configRepository.findByConfigKey(ConfigurationTYpe.AGENT_ALERT_1);
    List<ReceivingCountryAgent> receivingCountryAgents = receivingCountryAgentRepository.findAllByAgentStatusAndStatus(
            ReceivingCountryAgent.AgentStatus.APPROVED,
            ReceivingCountryAgent.EnableDisableStatus.ACTIVE
    );

    String json = config.getConfigJson();


    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.readTree(json);

    int days = node.get("noOfDays").asInt();


    // Process alerts for all agents for 30-day notification
    receivingCountryAgents.forEach(receivingCountryAgent -> {
        Optional<ReceivingCountryAgentDocument> optionalLicenceDoc = receivingCountryAgent.getDocuments().stream()
                .filter(doc -> doc.getType().equals(ReceivingCountryAgentDocument.DocumentType.AGREEMENT))
                .findFirst();
        String message = node.get("emailMessage").asText();

        message = message.replace("${name}", receivingCountryAgent.getAgentName());
        message = message.replace("${days}", String.valueOf(days));

        String finalMessage = message;
        optionalLicenceDoc.ifPresent(licenceDoc -> {
            Date expiryDate = licenceDoc.getExpiryDate();
            if (expiryDate != null) {
                // Send a notification if expiring in 30 days
                sendNotificationIfExpiring(receivingCountryAgent, expiryDate, days, finalMessage, ConfigurationTYpe.AGENT_ALERT_1);
            }
        });
    });
}
java spring amazon-web-services spring-boot kubernetes
1个回答
0
投票
  1. 如果您有数据库,则可以使用ShedLock来防止重复任务。它的工作原理是锁定数据库中的计划任务,因此只有一个副本可以运行它。您只需将 ShedLock 添加到您的项目中,使用 PostgreSQL 或 Redis 配置它,并注释您的预定方法来控制锁。

  2. 如果你想要一个无数据库的解决方案,Kubernetes领导人选举是一个不错的选择。它使用 Kubernetes 的内置机制来选举一个 pod 作为领导者,并且只有该领导者 pod 才会执行任务。如果您更喜欢坚持使用 Kubernetes 而不添加额外的基础设施,那么这种方法非常有用。

© www.soinside.com 2019 - 2024. All rights reserved.