INT-4477: Add getRole() to LeaderInitiator Context

JIRA: https://jira.spring.io/browse/INT-4477

When running multiple roles, it is useful to be able to determine the
role for a particular context, e.g. in an event.

* Docs

**cherry-pick to 5.0.x**

(cherry picked from commit 73dbdb8)
This commit is contained in:
Gary Russell
2018-05-31 10:54:35 -04:00
committed by Artem Bilan
parent 7f898a55ce
commit b413e0fb84
6 changed files with 83 additions and 13 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
package org.springframework.integration.leader;
import org.springframework.lang.Nullable;
/**
* Interface that defines the context for candidate leadership.
* Instances of this object are passed to {@link Candidate candidates}
@@ -27,6 +29,7 @@ package org.springframework.integration.leader;
* @author Patrick Peralta
* @author Janne Valkealahti
* @author Artem Bilan
* @author Gary Russell
*
*/
@FunctionalInterface
@@ -49,4 +52,14 @@ public interface Context {
// no-op
}
/**
* Get the role for the {@link Candidate}.
* @return the role.
* @since 5.0.6
*/
@Nullable
default String getRole() {
return null;
}
}

View File

@@ -58,6 +58,7 @@ import org.springframework.util.Assert;
* @author Vedran Pavic
* @author Glenn Renfro
* @author Kiel Boatman
* @author Gary Russell
*
* @since 4.3.1
*/
@@ -69,8 +70,6 @@ public class LockRegistryLeaderInitiator implements SmartLifecycle, DisposableBe
private static final Log logger = LogFactory.getLog(LockRegistryLeaderInitiator.class);
private static final Context NULL_CONTEXT = () -> false;
private final Object lifecycleMonitor = new Object();
/**
@@ -87,6 +86,20 @@ public class LockRegistryLeaderInitiator implements SmartLifecycle, DisposableBe
*/
private final Candidate candidate;
private final Context nullContext = new Context() {
@Override
public boolean isLeader() {
return false;
}
@Override
public String getRole() {
return LockRegistryLeaderInitiator.this.candidate.getRole();
}
};
/**
* Executor service for running leadership daemon.
*/
@@ -243,11 +256,11 @@ public class LockRegistryLeaderInitiator implements SmartLifecycle, DisposableBe
}
/**
* @return the context (or null if not running)
* @return the context.
*/
public Context getContext() {
if (this.leaderSelector == null) {
return NULL_CONTEXT;
return this.nullContext;
}
return this.leaderSelector.context;
}
@@ -520,6 +533,11 @@ public class LockRegistryLeaderInitiator implements SmartLifecycle, DisposableBe
}
}
@Override
public String getRole() {
return LockRegistryLeaderInitiator.this.candidate.getRole();
}
@Override
public String toString() {
return "LockContext{role=" + LockRegistryLeaderInitiator.this.candidate.getRole() +