Я выполнил шаги, описанные в этой статье:
Код: Выделить всё
https://medium.com/@pedrommj8/using-leader-election-with-spring-cloud-kubernetes-and-spring-scheduler-8f7ea3e3e694
Любая помощь или ресурсы будут полезны. очень признателен.
Спасибо!
Я выполнил шаги из статьи, указанной выше, в которой объясняется, как использовать Kubernetes ConfigMap для выборов лидера в Приложение Spring Boot с Spring Cloud Kubernetes. Я добавил необходимые конфигурации для создания механизма выбора лидера, ожидая, что только один экземпляр (лидер) в кластере Kubernetes будет выполнять запланированную задачу, а остальные будут ждать.
Код: Выделить всё
1- add dependencies in pom.xml
org.springframework.boot
spring-boot-starter-actuator
org.springframework.cloud
spring-cloud-kubernetes-fabric8-leader
3.0.2
1- create a sheduled task
@Component
public class ScheduledTasks {
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
private ManagerContext managerContext;
public ScheduledTasks(ManagerContext managerContext){
this.managerContext = managerContext;
}
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
if (isLeader()) {
// Perform the task
log.info("The time is now {}", dateFormat.format(new Date()));
} else {
// Not the leader instance, wait until becoming the leader
log.info("I am not an leader");
}
}
private boolean isLeader() {
// Logic to check if this instance is the leader
return managerContext.getContext() != null; // Modify the logic to check real leadership
}
}
3- Edit the application.properties file and add the following configurations:
spring.cloud.kubernetes.leader.role=world
# Configmap to which leader election metadata will be saved
spring.cloud.kubernetes.leader.config-map-name=my-config-map
4- add new component to listen on OnGrantedEvent and OnRevokedEvent and Hold the role in the context
/**
* Handle a notification that this instance has become a leader.
* @param event on granted event
*/
@EventListener
public void handleEvent(OnGrantedEvent event) {
System.out.println(String.format("'%s' leadership granted", event.getRole()));
this.context = event.getContext();
managerContext.setContext(this.context);
}
/**
* Handle a notification that this instance's leadership has been revoked.
* @param event on revoked event
*/
@EventListener
public void handleEvent(OnRevokedEvent event) {
System.out.println(String.format("'%s' leadership revoked", event.getRole()));
this.context = null;
managerContext.setContext(null);
}
5- Creating the configMap that will be used by the application
6- creating the Role and RoleBinding ensure only the specific service account has access to manage the ConfigMap.
Подробнее здесь: https://stackoverflow.com/questions/790 ... ion-v2-7-d