Skip to content

Instantly share code, notes, and snippets.

@Arbow
Created November 8, 2012 07:38
Show Gist options
  • Save Arbow/4037420 to your computer and use it in GitHub Desktop.
Save Arbow/4037420 to your computer and use it in GitHub Desktop.
Failover locator in spymemcached
public class FailoverNodeLocator implements NodeLocator {
private MemcachedNode[] nodes;
public FailoverNodeLocator(List<MemcachedNode> n) {
assert n.size() > 1;
nodes = n.toArray(new MemcachedNode[n.size()]);
}
public FailoverNodeLocator(MemcachedNode[] n) {
nodes = n;
}
@Override
public MemcachedNode getPrimary(String k) {
return nodes[0];
}
@Override
public Iterator<MemcachedNode> getSequence(String k) {
return new NodeIterator(getServerForKey(k));
}
private int getServerForKey(String key) {
return 0;
}
@Override
public Collection<MemcachedNode> getAll() {
return Arrays.asList(nodes);
}
@Override
public NodeLocator getReadonlyCopy() {
MemcachedNode[] n = new MemcachedNode[nodes.length];
for (int i = 0; i < nodes.length; i++) {
n[i] = new MemcachedNodeROImpl(nodes[i]);
}
return new FailoverNodeLocator(n);
}
@Override
public void updateLocator(List<MemcachedNode> newNodes) {
this.nodes = newNodes.toArray(new MemcachedNode[newNodes.size()]);
}
class NodeIterator implements Iterator<MemcachedNode> {
private final int start;
private int next = 0;
public NodeIterator(int keyStart) {
start = keyStart;
next = start;
computeNext();
assert next >= 0 || nodes.length == 1 : "Starting sequence at " + start + " of " + nodes.length + " next is " + next;
}
public boolean hasNext() {
return next >= 0;
}
private void computeNext() {
if (++next >= nodes.length) {
next = 0;
}
if (next == start) {
next = -1;
}
}
public MemcachedNode next() {
try {
return nodes[next];
} finally {
computeNext();
}
}
public void remove() {
throw new UnsupportedOperationException("Can't remove a node");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment