forked from dork/tarantool-java
-
Notifications
You must be signed in to change notification settings - Fork 19
add round robin fail-over for a client #98
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Totktonada
merged 1 commit into
tarantool:master
from
ztarvos:add-round-robin-reconnect-strategy
Dec 13, 2018
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
182 changes: 182 additions & 0 deletions
182
src/main/java/org/tarantool/RoundRobinSocketProviderImpl.java
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,182 @@ | ||
package org.tarantool; | ||
|
||
import java.io.IOException; | ||
import java.net.InetSocketAddress; | ||
import java.nio.channels.SocketChannel; | ||
import java.util.Arrays; | ||
|
||
/** | ||
* Basic reconnection strategy that changes addresses in a round-robin fashion. | ||
* To be used with {@link TarantoolClientImpl}. | ||
*/ | ||
public class RoundRobinSocketProviderImpl implements SocketChannelProvider { | ||
/** Timeout to establish socket connection with an individual server. */ | ||
private int timeout; // 0 is infinite. | ||
/** Limit of retries. */ | ||
private int retriesLimit = -1; // No-limit. | ||
/** Server addresses as configured. */ | ||
private final String[] addrs; | ||
/** Socket addresses. */ | ||
private final InetSocketAddress[] sockAddrs; | ||
/** Current position within {@link #sockAddrs} array. */ | ||
private int pos; | ||
|
||
/** | ||
* Constructs an instance. | ||
* | ||
* @param addrs Array of addresses in a form of [host]:[port]. | ||
*/ | ||
public RoundRobinSocketProviderImpl(String... addrs) { | ||
if (addrs == null || addrs.length == 0) | ||
throw new IllegalArgumentException("addrs is null or empty."); | ||
|
||
this.addrs = Arrays.copyOf(addrs, addrs.length); | ||
|
||
sockAddrs = new InetSocketAddress[this.addrs.length]; | ||
|
||
for (int i = 0; i < this.addrs.length; i++) { | ||
sockAddrs[i] = parseAddress(this.addrs[i]); | ||
} | ||
} | ||
|
||
/** | ||
* @return Configured addresses in a form of [host]:[port]. | ||
*/ | ||
public String[] getAddresses() { | ||
return this.addrs; | ||
} | ||
|
||
/** | ||
* Sets maximum amount of time to wait for a socket connection establishment | ||
* with an individual server. | ||
* | ||
* Zero means infinite timeout. | ||
* | ||
* @param timeout Timeout value, ms. | ||
* @return {@code this}. | ||
* @throws IllegalArgumentException If timeout is negative. | ||
*/ | ||
public RoundRobinSocketProviderImpl setTimeout(int timeout) { | ||
if (timeout < 0) | ||
throw new IllegalArgumentException("timeout is negative."); | ||
|
||
this.timeout = timeout; | ||
|
||
return this; | ||
} | ||
|
||
/** | ||
* @return Maximum amount of time to wait for a socket connection establishment | ||
* with an individual server. | ||
*/ | ||
public int getTimeout() { | ||
return timeout; | ||
} | ||
|
||
/** | ||
* Sets maximum amount of reconnect attempts to be made before an exception is raised. | ||
* The retry count is maintained by a {@link #get(int, Throwable)} caller | ||
* when a socket level connection was established. | ||
* | ||
* Negative value means unlimited. | ||
* | ||
* @param retriesLimit Limit of retries to use. | ||
* @return {@code this}. | ||
*/ | ||
public RoundRobinSocketProviderImpl setRetriesLimit(int retriesLimit) { | ||
this.retriesLimit = retriesLimit; | ||
|
||
return this; | ||
} | ||
|
||
/** | ||
* @return Maximum reconnect attempts to make before raising exception. | ||
*/ | ||
public int getRetriesLimit() { | ||
return retriesLimit; | ||
} | ||
|
||
/** {@inheritDoc} */ | ||
@Override | ||
public SocketChannel get(int retryNumber, Throwable lastError) { | ||
if (areRetriesExhausted(retryNumber)) { | ||
throw new CommunicationException("Connection retries exceeded.", lastError); | ||
} | ||
int attempts = getAddressCount(); | ||
long deadline = System.currentTimeMillis() + timeout * attempts; | ||
while (!Thread.currentThread().isInterrupted()) { | ||
SocketChannel channel = null; | ||
try { | ||
channel = SocketChannel.open(); | ||
InetSocketAddress addr = getNextSocketAddress(); | ||
channel.socket().connect(addr, timeout); | ||
return channel; | ||
} catch (IOException e) { | ||
if (channel != null) { | ||
try { | ||
channel.close(); | ||
} catch (IOException ignored) { | ||
// No-op. | ||
} | ||
} | ||
long now = System.currentTimeMillis(); | ||
if (deadline <= now) { | ||
throw new CommunicationException("Connection time out.", e); | ||
} | ||
if (--attempts == 0) { | ||
// Tried all addresses without any lack, but still have time. | ||
attempts = getAddressCount(); | ||
try { | ||
Thread.sleep((deadline - now) / attempts); | ||
} catch (InterruptedException ignored) { | ||
Thread.currentThread().interrupt(); | ||
} | ||
} | ||
} | ||
} | ||
throw new CommunicationException("Thread interrupted.", new InterruptedException()); | ||
} | ||
|
||
/** | ||
* @return Number of configured addresses. | ||
*/ | ||
protected int getAddressCount() { | ||
return sockAddrs.length; | ||
} | ||
|
||
/** | ||
* @return Socket address to use for the next reconnection attempt. | ||
*/ | ||
protected InetSocketAddress getNextSocketAddress() { | ||
InetSocketAddress res = sockAddrs[pos]; | ||
pos = (pos + 1) % sockAddrs.length; | ||
return res; | ||
} | ||
|
||
/** | ||
* Parse a string address in the form of [host]:[port] | ||
* and builds a socket address. | ||
* | ||
* @param addr Server address. | ||
* @return Socket address. | ||
*/ | ||
protected InetSocketAddress parseAddress(String addr) { | ||
int idx = addr.indexOf(':'); | ||
String host = (idx < 0) ? addr : addr.substring(0, idx); | ||
int port = (idx < 0) ? 3301 : Integer.parseInt(addr.substring(idx + 1)); | ||
return new InetSocketAddress(host, port); | ||
} | ||
|
||
/** | ||
* Provides a decision on whether retries limit is hit. | ||
* | ||
* @param retries Current count of retries. | ||
* @return {@code true} if retries are exhausted. | ||
*/ | ||
private boolean areRetriesExhausted(int retries) { | ||
int limit = getRetriesLimit(); | ||
if (limit < 0) | ||
return false; | ||
return retries >= limit; | ||
} | ||
} |
This file contains hidden or 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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.