Top Description Inners Fields Constructors Methods
com.mysql.cj.jdbc.ha

public Class LoadBalancedConnectionProxy

extends MultiHostConnectionProxy
implements PingTarget
Class Inheritance
All Implemented Interfaces
com.mysql.cj.PingTarget
Static Imports
com.mysql.cj.util.StringUtils.isNullOrEmpty

A proxy for a dynamic com.mysql.cj.jdbc.JdbcConnection implementation that load balances requests across a series of MySQL JDBC connections, where the balancing takes place at transaction commit. Therefore, for this to work (at all), you must use transactions, even if only reading data. This implementation will invalidate connections that it detects have had communication errors when processing a request. Problematic hosts will be added to a global blocklist for loadBalanceBlocklistTimeout ms, after which they will be removed from the blocklist and made eligible once again to be selected for new connections. This implementation is thread-safe, but it's questionable whether sharing a connection instance amongst threads is a good idea, given that transactions are scoped to connections in JDBC.

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static class
LoadBalancedConnectionProxy.NullLoadBalancedConnectionProxy

A LoadBalancedConnection proxy that provides null-functionality.

Field Summary

Modifier and TypeField and Description
private BalanceStrategy
private ConnectionGroup
private long
private Map<ConnectionImpl, String>
private LoadBalanceExceptionChecker
private static Map<String, Long>
private int
private int
private Map<String, Integer>
private Set<String>
private static Class<?>[]
private boolean
protected Map<String, ConnectionImpl>
private static final Lock
private static LoadBalancedConnection
private long[]
private int
private long
private long
private long
Inherited from com.mysql.cj.jdbc.ha.MultiHostConnectionProxy:
autoReconnectclosedExplicitlyclosedReasonconnectionUrlcurrentConnectionhostsListisClosedlastExceptionDealtWithparentProxyConnectionthisAsConnectiontopProxyConnection

Constructor Summary

AccessConstructor and Description
public
LoadBalancedConnectionProxy(ConnectionUrl
The connection URL containing the hosts to load balance.
connectionUrl
)

Creates a proxy for java.sql.Connection that routes requests between the hosts in the connection URL.

Method Summary

Modifier and TypeMethod and Description
public boolean

Returns:

true if host was added and false if the host list already contains it
addHost
(String
The host to be added.
hostPortPair
)

Adds a host to the hosts list.

public void
addToGlobalBlocklist(String
The host to be blocklisted.
host
,
long
The blocklist timeout for this entry.
timeout
)

Adds a host to the blocklist with the given timeout.

public void
addToGlobalBlocklist(String
The host to be blocklisted.
host
)

Adds a host to the blocklist.

private void
closeAllConnections()

Closes all live connections.

public ConnectionImpl

Returns:

The new Connection instance.
createConnectionForHost
(HostInfo
The host info instance.
hostInfo
)

Overrides com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.createConnectionForHost.

Creates a new physical connection for the given HostInfo and updates required internal mappings and statistics for that connection.

public ConnectionImpl

Returns:

The new Connection instance.
createConnectionForHost
(String
The host:port pair identifying the host to connect to.
hostPortPair
)

Creates a new physical connection for the given host:port info.

public static LoadBalancedConnection

Returns:

A LoadBalancedConnection proxy.
createProxyInstance
(ConnectionUrl
The connection URL containing the hosts in a load-balance setup.
connectionUrl
)

Static factory to create LoadBalancedConnection instances.

pack-priv void
doAbort(Executor
executor
executor
)

Implements abstract com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.doAbort.

Aborts all live connections, using the provided Executor.

pack-priv void
doAbortInternal()

Implements abstract com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.doAbortInternal.

Aborts all live connections

pack-priv void
doClose()

Implements abstract com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.doClose.

Closes all live connections.

public void
doPing()

Implements com.mysql.cj.PingTarget.doPing.

Pings live connections.

public long
public long
public String
public long
public Map<String, Long>

Returns:

A local hosts blocklist.
getGlobalBlocklist
()

Returns a local hosts blocklist, while cleaning up expired records from the global blocklist, or a blocklist with the hosts to be removed.

pack-priv JdbcConnection

Returns:

The connection object instance that wraps 'this'.
getNewWrapperForThisAsConnection
()

Overrides com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.getNewWrapperForThisAsConnection.

Wraps this object with a new load balanced Connection instance.

pack-priv static LoadBalancedConnection
public long
public long
public boolean
pack-priv void
invalidateConnection(JdbcConnection
connection
conn
)

Overrides com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.invalidateConnection.

Closes specified connection and removes it from required mappings.

pack-priv Object
invokeMore(Object
proxy object
proxy
,
Method
method to invoke
method
,
Object[]
method parameters
args
)

Implements abstract com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.invokeMore.

Proxies method invocation on the java.sql.Connection interface, trapping "close", "isClosed" and "commit/rollback" to switch connections for load balancing.

public boolean

Returns:

true if host blocklist management was enabled
isGlobalBlocklistEnabled
()

Checks if host blocklist management was enabled.

pack-priv boolean
isSourceConnection()

Implements abstract com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.isSourceConnection.

Always returns 'true' as there are no "sources" and "replicas" in this type of connection.

public void
pickNewConnection()

Implements abstract com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.pickNewConnection.

Picks the "best" connection to use for the next transaction based on the BalanceStrategy in use.

protected void
propagateProxyDown(JdbcConnection
The top level connection in the multi-host connections chain.
proxyConn
)

Overrides com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.propagateProxyDown.

Propagates the connection proxy down through all live connections.

public void
removeFromGlobalBlocklist(String
The host to be removed from the blocklist.
host
)

Removes a host from the blocklist.

public void
removeHost(String
The host to be removed.
hostPortPair
)

Removes a host from the host list.

public void
removeHostWhenNotInUse(String
The host to be removed.
hostPortPair
)

Removes a host from the host list, allowing it some time to be released gracefully if needed.

pack-priv boolean

Returns:

true if the given exception should trigger a connection fail-over
shouldExceptionTriggerConnectionSwitch
(Throwable
The Exception instance to check.
t
)

Implements abstract com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.shouldExceptionTriggerConnectionSwitch.

Consults the registered LoadBalanceExceptionChecker if the given exception should trigger a connection fail-over.

public boolean
pack-priv void
syncSessionState(JdbcConnection
The connection where to get state from.
source
,
JdbcConnection
The connection where to set state.
target
,
boolean
The new read-only status.
readOnly
)

Overrides com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.syncSessionState.

Synchronizes session state between two connections, allowing to override the read-only status.

Inherited from com.mysql.cj.jdbc.ha.MultiHostConnectionProxy:
allowedOnClosedConnectiondealWithInvocationExceptiongetLockgetNewJdbcInterfaceProxygetParentProxygetProxyinitializeHostsSpecsinvalidateCurrentConnectioninvokeproxyIfReturnTypeIsJdbcInterfacesetProxysyncSessionState

Field Detail

balancerback to summary
private BalanceStrategy balancer
connectionGroupback to summary
private ConnectionGroup connectionGroup
connectionGroupProxyIDback to summary
private long connectionGroupProxyID
connectionsToHostsMapback to summary
private Map<ConnectionImpl, String> connectionsToHostsMap
exceptionCheckerback to summary
private LoadBalanceExceptionChecker exceptionChecker
globalBlocklistback to summary
private static Map<String, Long> globalBlocklist
globalBlocklistTimeoutback to summary
private int globalBlocklistTimeout
hostRemovalGracePeriodback to summary
private int hostRemovalGracePeriod
hostsToListIndexMapback to summary
private Map<String, Integer> hostsToListIndexMap
hostsToRemoveback to summary
private Set<String> hostsToRemove
INTERFACES_TO_PROXYback to summary
private static Class<?>[] INTERFACES_TO_PROXY
inTransactionback to summary
private boolean inTransaction
liveConnectionsback to summary
protected Map<String, ConnectionImpl> liveConnections
LOCKback to summary
private static final Lock LOCK
nullLBConnectionInstanceback to summary
private static LoadBalancedConnection nullLBConnectionInstance
responseTimesback to summary
private long[] responseTimes
retriesAllDownback to summary
private int retriesAllDown
totalPhysicalConnectionsback to summary
private long totalPhysicalConnections
transactionCountback to summary
private long transactionCount
transactionStartTimeback to summary
private long transactionStartTime

Constructor Detail

LoadBalancedConnectionProxyback to summary
public LoadBalancedConnectionProxy(ConnectionUrl connectionUrl) throws SQLException

Creates a proxy for java.sql.Connection that routes requests between the hosts in the connection URL.

Parameters
connectionUrl:ConnectionUrl

The connection URL containing the hosts to load balance.

Exceptions
SQLException:
if an error occurs

Method Detail

addHostback to summary
public boolean addHost(String hostPortPair)

Adds a host to the hosts list.

Parameters
hostPortPair:String

The host to be added.

Returns:boolean

true if host was added and false if the host list already contains it

addToGlobalBlocklistback to summary
public void addToGlobalBlocklist(String host, long timeout)

Adds a host to the blocklist with the given timeout.

Parameters
host:String

The host to be blocklisted.

timeout:long

The blocklist timeout for this entry.

addToGlobalBlocklistback to summary
public void addToGlobalBlocklist(String host)

Adds a host to the blocklist.

Parameters
host:String

The host to be blocklisted.

closeAllConnectionsback to summary
private void closeAllConnections()

Closes all live connections.

createConnectionForHostback to summary
public ConnectionImpl createConnectionForHost(HostInfo hostInfo) throws SQLException

Overrides com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.createConnectionForHost.

Creates a new physical connection for the given HostInfo and updates required internal mappings and statistics for that connection.

Parameters
hostInfo:HostInfo

The host info instance.

Returns:ConnectionImpl

The new Connection instance.

Annotations
@Override
Exceptions
SQLException:
if an error occurs
createConnectionForHostback to summary
public ConnectionImpl createConnectionForHost(String hostPortPair) throws SQLException

Creates a new physical connection for the given host:port info. If the this connection's connection URL knows about this host:port then its host info is used, otherwise a new host info based on current connection URL defaults is spawned.

Parameters
hostPortPair:String

The host:port pair identifying the host to connect to.

Returns:ConnectionImpl

The new Connection instance.

Exceptions
SQLException:
if an error occurs
createProxyInstanceback to summary
public static LoadBalancedConnection createProxyInstance(ConnectionUrl connectionUrl) throws SQLException

Static factory to create LoadBalancedConnection instances.

Parameters
connectionUrl:ConnectionUrl

The connection URL containing the hosts in a load-balance setup.

Returns:LoadBalancedConnection

A LoadBalancedConnection proxy.

Exceptions
SQLException:
if an error occurs
doAbortback to summary
pack-priv void doAbort(Executor executor)

Implements abstract com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.doAbort.

Aborts all live connections, using the provided Executor.

Parameters
executor:Executor

Doc from com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.doAbort.

executor

Annotations
@Override
doAbortInternalback to summary
pack-priv void doAbortInternal()

Implements abstract com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.doAbortInternal.

Aborts all live connections

Annotations
@Override
doCloseback to summary
pack-priv void doClose()

Implements abstract com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.doClose.

Closes all live connections.

Annotations
@Override
doPingback to summary
public void doPing() throws SQLException

Implements com.mysql.cj.PingTarget.doPing.

Pings live connections.

Annotations
@Override
Exceptions
SQLException:
if an error occurs
getActivePhysicalConnectionCountback to summary
public long getActivePhysicalConnectionCount()
getConnectionGroupProxyIDback to summary
public long getConnectionGroupProxyID()
getCurrentActiveHostback to summary
public String getCurrentActiveHost()
getCurrentTransactionDurationback to summary
public long getCurrentTransactionDuration()
getGlobalBlocklistback to summary
public Map<String, Long> getGlobalBlocklist()

Returns a local hosts blocklist, while cleaning up expired records from the global blocklist, or a blocklist with the hosts to be removed.

Returns:Map<String, Long>

A local hosts blocklist.

getNewWrapperForThisAsConnectionback to summary
pack-priv JdbcConnection getNewWrapperForThisAsConnection() throws SQLException

Overrides com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.getNewWrapperForThisAsConnection.

Wraps this object with a new load balanced Connection instance.

Returns:JdbcConnection

The connection object instance that wraps 'this'.

Annotations
@Override
Exceptions
SQLException:
if an error occurs
getNullLoadBalancedConnectionInstanceback to summary
pack-priv static LoadBalancedConnection getNullLoadBalancedConnectionInstance()
getTotalPhysicalConnectionCountback to summary
public long getTotalPhysicalConnectionCount()
getTransactionCountback to summary
public long getTransactionCount()
inTransactionback to summary
public boolean inTransaction()
invalidateConnectionback to summary
pack-priv void invalidateConnection(JdbcConnection conn) throws SQLException

Overrides com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.invalidateConnection.

Closes specified connection and removes it from required mappings.

Parameters
conn:JdbcConnection

connection

Annotations
@Override
Exceptions
SQLException:
if an error occurs
invokeMoreback to summary
pack-priv Object invokeMore(Object proxy, Method method, Object[] args) throws Throwable

Implements abstract com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.invokeMore.

Proxies method invocation on the java.sql.Connection interface, trapping "close", "isClosed" and "commit/rollback" to switch connections for load balancing. This is the continuation of MultiHostConnectionProxy#invoke(Object, Method, Object[]).

Parameters
proxy:Object

Doc from com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.invokeMore.

proxy object

method:Method

Doc from com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.invokeMore.

method to invoke

args:Object[]

Doc from com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.invokeMore.

method parameters

Returns:Object

Doc from com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.invokeMore.

method result

Annotations
@Override
Exceptions
Throwable:

Doc from com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.invokeMore.

if an error occurs

isGlobalBlocklistEnabledback to summary
public boolean isGlobalBlocklistEnabled()

Checks if host blocklist management was enabled.

Returns:boolean

true if host blocklist management was enabled

isSourceConnectionback to summary
pack-priv boolean isSourceConnection()

Implements abstract com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.isSourceConnection.

Always returns 'true' as there are no "sources" and "replicas" in this type of connection.

Returns:boolean

Doc from com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.isSourceConnection.

true if current connection is to a source host

Annotations
@Override
pickNewConnectionback to summary
public void pickNewConnection() throws SQLException

Implements abstract com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.pickNewConnection.

Picks the "best" connection to use for the next transaction based on the BalanceStrategy in use.

Annotations
@Override
Exceptions
SQLException:
if an error occurs
propagateProxyDownback to summary
protected void propagateProxyDown(JdbcConnection proxyConn)

Overrides com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.propagateProxyDown.

Propagates the connection proxy down through all live connections.

Parameters
proxyConn:JdbcConnection

The top level connection in the multi-host connections chain.

Annotations
@Override
removeFromGlobalBlocklistback to summary
public void removeFromGlobalBlocklist(String host)

Removes a host from the blocklist.

Parameters
host:String

The host to be removed from the blocklist.

removeHostback to summary
public void removeHost(String hostPortPair) throws SQLException

Removes a host from the host list.

Parameters
hostPortPair:String

The host to be removed.

Exceptions
SQLException:
if an error occurs
removeHostWhenNotInUseback to summary
public void removeHostWhenNotInUse(String hostPortPair) throws SQLException

Removes a host from the host list, allowing it some time to be released gracefully if needed.

Parameters
hostPortPair:String

The host to be removed.

Exceptions
SQLException:
if an error occurs
shouldExceptionTriggerConnectionSwitchback to summary
pack-priv boolean shouldExceptionTriggerConnectionSwitch(Throwable t)

Implements abstract com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.shouldExceptionTriggerConnectionSwitch.

Consults the registered LoadBalanceExceptionChecker if the given exception should trigger a connection fail-over.

Parameters
t:Throwable

The Exception instance to check.

Returns:boolean

true if the given exception should trigger a connection fail-over

Annotations
@Override
shouldExceptionTriggerFailoverback to summary
public boolean shouldExceptionTriggerFailover(Throwable t)

Deprecated

Annotations
@Deprecated
syncSessionStateback to summary
pack-priv void syncSessionState(JdbcConnection source, JdbcConnection target, boolean readOnly) throws SQLException

Overrides com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.syncSessionState.

Doc from com.mysql.cj.jdbc.ha.MultiHostConnectionProxy.syncSessionState.

Synchronizes session state between two connections, allowing to override the read-only status.

Parameters
source:JdbcConnection

The connection where to get state from.

target:JdbcConnection

The connection where to set state.

readOnly:boolean

The new read-only status.

Annotations
@Override
Exceptions
SQLException:
if an error occurs
com.mysql.cj.jdbc.ha back to summary

private Class LoadBalancedConnectionProxy.NullLoadBalancedConnectionProxy

extends Object
implements InvocationHandler
Class Inheritance
  • java.lang.Object
  • com.mysql.cj.jdbc.ha.LoadBalancedConnectionProxy.NullLoadBalancedConnectionProxy
All Implemented Interfaces
java.lang.reflect.InvocationHandler

A LoadBalancedConnection proxy that provides null-functionality. It can be used as a replacement of the null keyword in the places where a LoadBalancedConnection object cannot be effectively null because that would be a potential source of NPEs.

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public Object
invoke(Object
the proxy instance that the method was invoked on
proxy
,
Method
the Method instance corresponding to the interface method invoked on the proxy instance. The declaring class of the Method object will be the interface that the method was declared in, which may be a superinterface of the proxy interface that the proxy class inherits the method through.
method
,
Object[]
an array of objects containing the values of the arguments passed in the method invocation on the proxy instance, or null if interface method takes no arguments. Arguments of primitive types are wrapped in instances of the appropriate primitive wrapper class, such as java.lang.Integer or java.lang.Boolean.
args
)

Implements java.lang.reflect.InvocationHandler.invoke.

Processes a method invocation on a proxy instance and returns the result.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Constructor Detail

NullLoadBalancedConnectionProxyback to summary
public NullLoadBalancedConnectionProxy()

Method Detail

invokeback to summary
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable

Implements java.lang.reflect.InvocationHandler.invoke.

Doc from java.lang.reflect.InvocationHandler.invoke.

Processes a method invocation on a proxy instance and returns the result. This method will be invoked on an invocation handler when a method is invoked on a proxy instance that it is associated with.

Parameters
proxy:Object

the proxy instance that the method was invoked on

method:Method

the Method instance corresponding to the interface method invoked on the proxy instance. The declaring class of the Method object will be the interface that the method was declared in, which may be a superinterface of the proxy interface that the proxy class inherits the method through.

args:Object[]

an array of objects containing the values of the arguments passed in the method invocation on the proxy instance, or null if interface method takes no arguments. Arguments of primitive types are wrapped in instances of the appropriate primitive wrapper class, such as java.lang.Integer or java.lang.Boolean.

Returns:Object

the value to return from the method invocation on the proxy instance. If the declared return type of the interface method is a primitive type, then the value returned by this method must be an instance of the corresponding primitive wrapper class; otherwise, it must be a type assignable to the declared return type. If the value returned by this method is null and the interface method's return type is primitive, then a NullPointerException will be thrown by the method invocation on the proxy instance. If the value returned by this method is otherwise not compatible with the interface method's declared return type as described above, a ClassCastException will be thrown by the method invocation on the proxy instance.

Annotations
@Override
Exceptions
Throwable:
the exception to throw from the method invocation on the proxy instance. The exception's type must be assignable either to any of the exception types declared in the throws clause of the interface method or to the unchecked exception types java.lang.RuntimeException or java.lang.Error. If a checked exception is thrown by this method that is not assignable to any of the exception types declared in the throws clause of the interface method, then an UndeclaredThrowableException containing the exception that was thrown by this method will be thrown by the method invocation on the proxy instance.