Last active
December 17, 2015 18:19
-
-
Save kay/5652895 to your computer and use it in GitHub Desktop.
FailoverManager.java
Used in http://seekingconsistency.com/2013-05-26/simple-cheap-and-effective-high-availability/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FailoverManager implements AutoCloseable, ChannelListener, Receiver { | |
private static final Logger LOGGER = LoggerFactory.getLogger(FailoverManager.class); | |
private static final String HA_CLUSTER = "ha-cluster"; | |
private final JChannel channel; | |
private final int maximumClusterSize; | |
private final LeadershipResolver decider; | |
public FailoverManager(final String configName, | |
final String applicationGroup, | |
final int maximumClusterSize, | |
final LeadershipListener leadershipListener) | |
throws HighAvailabilityException { | |
if (maximumClusterSize < 3) { | |
throw new IllegalArgumentException("Cluster must contain at least 3 members"); | |
} | |
this.maximumClusterSize = maximumClusterSize; | |
try { | |
this.channel = new JChannel(configName); | |
this.channel.addChannelListener(this); | |
this.channel.setReceiver(this); | |
this.decider = new LeadershipResolver(this.channel, applicationGroup, leadershipListener); | |
this.channel.connect(HA_CLUSTER); | |
} catch (final Exception e) { | |
throw new HighAvailabilityException("Failed to initialise channel '" + applicationGroup | |
+ "' and connect to '" + HA_CLUSTER + "'", e); | |
} | |
} | |
private boolean isMajority(final int currentClusterSize) { | |
final int majorityThreshold = (this.maximumClusterSize / 2) + 1; | |
return (currentClusterSize >= majorityThreshold); | |
} | |
@Override | |
public void viewAccepted(final View newView) { | |
LOGGER.info("View accepted {}", newView); | |
if (isMajority(newView.getMembers().size())) { | |
this.decider.tryLeadership(); | |
} else { | |
this.decider.surrenderLeadership(); | |
} | |
} | |
@Override | |
public void close() { | |
this.channel.close(); | |
this.decider.close(); | |
} | |
/* Other methods omitted for brevity */ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment