简体   繁体   English

如何在 k8s 中复制的 pod 中拥有只执行一次的逻辑(一段代码)?

[英]How to have a logic (piece of code) that executes only once inside pods which are replicated in k8s?

I have a cronjob which is inside my golang application code.我的 golang 应用程序代码中有一个 cronjob。 now, this code is inside a container which is inside a pod现在,这段代码在一个容器内,该容器在一个 pod 内

What happens :会发生什么
Suppose I have a cronjob to send emails every Sunday.假设我有一个 cronjob 每周日发送电子邮件。
The application starts to run and the cronjobs are created as soon as the application starts.应用程序开始运行,并在应用程序启动后立即创建 cronjobs。
Now, If I have 3 such pods, the applications starts thrice in each pod and would have it's own cronjob, so the emails will be sent three times.现在,如果我有 3 个这样的 pod,应用程序会在每个 pod 中启动三次,并且会有自己的 cronjob,因此电子邮件将被发送 3 次。

What I want :我想要什么
The email should be sent only once ie all cronjobs should run only once independent of how many replicas I create email 应该只发送一次,即所有 cronjobs 应该只运行一次,与我创建的副本数量无关

How can I achieve this?我怎样才能做到这一点?
Preferably: I would like to have the jobs inside the application because if I separate them out, I will have to call the API endpoint instead of the service directly.最好:我希望在应用程序中拥有这些作业,因为如果我将它们分开,我将不得不调用 API 端点而不是直接调用服务。

TL;DR: Perhaps you need to rethink the value of co-locating the cronjobs with the function exposed via the API. TL;DR:也许您需要重新考虑将 cronjobs 与通过 API 暴露的 function 共同定位的价值。

ie put the cronjobs in a separate pod with no replicas.即将 cronjobs 放在一个没有副本的单独 pod 中。

From the information available, that would seem to solve your problem most easily.从可用的信息来看,这似乎最容易解决您的问题。

The question then arises, what value was gained or problem solved ( other than convenience) by co-locating the cronjobs in the first place?然后问题出现了,首先通过共同定位 cronjobs 获得了什么价值或解决了什么问题(除了方便)?

If there was no other problem, or that problem is more easily solved in other ways than the additional complexity involved in solving the problem that the co-location solution has created , then you have your answer.如果没有其他问题,或者该问题比解决托管解决方案所产生的问题所涉及的额外复杂性更容易以其他方式解决,那么您就有了答案。

Another test to apply would be which solution architecture would be easier for someone to understand (and in the future extend, modify or maintain):另一个要应用的测试是哪种解决方案架构更容易让人理解(以及将来扩展、修改或维护):

  1. separate cronjobs, running only once, and doing their work via an API单独的 cronjobs,只运行一次,并通过 API 完成它们的工作

  2. multiple cronjobs seemingly intentionally placed in a replicaset but with some complex coordination mechanism that contrives to ensure that of these multiple jobs only one instance is actually effective and the others rendered essentially inoperative多个 cronjobs 看似有意放置在一个副本集中,但具有一些复杂的协调机制,旨在确保在这些多个作业中只有一个实例实际上是有效的,而其他实例基本上是无效的

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

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