Package com.mysql.cj.jdbc.ha
Class LoadBalancedConnectionProxy
java.lang.Object
com.mysql.cj.jdbc.ha.MultiHostConnectionProxy
com.mysql.cj.jdbc.ha.LoadBalancedConnectionProxy
- All Implemented Interfaces:
PingTarget,java.lang.reflect.InvocationHandler
public class LoadBalancedConnectionProxy extends MultiHostConnectionProxy implements PingTarget
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.
-
Field Summary
Fields Modifier and Type Field Description protected java.util.Map<java.lang.String,ConnectionImpl>liveConnectionsFields inherited from class com.mysql.cj.jdbc.ha.MultiHostConnectionProxy
autoReconnect, closedExplicitly, closedReason, connectionUrl, currentConnection, hostsList, isClosed, lastExceptionDealtWith, thisAsConnection -
Constructor Summary
Constructors Constructor Description LoadBalancedConnectionProxy(ConnectionUrl connectionUrl)Creates a proxy for java.sql.Connection that routes requests between the hosts in the connection URL. -
Method Summary
Modifier and Type Method Description booleanaddHost(java.lang.String hostPortPair)Adds a host to the hosts list.voidaddToGlobalBlacklist(java.lang.String host)Deprecated.voidaddToGlobalBlacklist(java.lang.String host, long timeout)Deprecated.voidaddToGlobalBlocklist(java.lang.String host)Adds a host to the blocklist.voidaddToGlobalBlocklist(java.lang.String host, long timeout)Adds a host to the blocklist with the given timeout.ConnectionImplcreateConnectionForHost(HostInfo hostInfo)Creates a new physical connection for the givenHostInfoand updates required internal mappings and statistics for that connection.ConnectionImplcreateConnectionForHost(java.lang.String hostPortPair)Creates a new physical connection for the given host:port info.static LoadBalancedConnectioncreateProxyInstance(ConnectionUrl connectionUrl)Static factory to createLoadBalancedConnectioninstances.protected voiddoAbort(java.util.concurrent.Executor executor)Aborts all live connections, using the provided Executor.protected voiddoAbortInternal()Aborts all live connectionsprotected voiddoClose()Closes all live connections.voiddoPing()Pings live connections.longgetActivePhysicalConnectionCount()longgetConnectionGroupProxyID()java.lang.StringgetCurrentActiveHost()longgetCurrentTransactionDuration()java.util.Map<java.lang.String,java.lang.Long>getGlobalBlacklist()Deprecated.java.util.Map<java.lang.String,java.lang.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.longgetTotalPhysicalConnectionCount()longgetTransactionCount()booleaninTransaction()protected voidinvalidateConnection(JdbcConnection conn)Closes specified connection and removes it from required mappings.java.lang.ObjectinvokeMore(java.lang.Object proxy, java.lang.reflect.Method method, java.lang.Object[] args)Proxies method invocation on the java.sql.Connection interface, trapping "close", "isClosed" and "commit/rollback" to switch connections for load balancing.booleanisGlobalBlacklistEnabled()Deprecated.booleanisGlobalBlocklistEnabled()Checks if host blocklist management was enabled.protected booleanisSourceConnection()Always returns 'true' as there are no "sources" and "replicas" in this type of connection.voidpickNewConnection()Picks the "best" connection to use for the next transaction based on the BalanceStrategy in use.protected voidpropagateProxyDown(JdbcConnection proxyConn)Propagates the connection proxy down through all live connections.voidremoveFromGlobalBlacklist(java.lang.String host)Deprecated.voidremoveFromGlobalBlocklist(java.lang.String host)Removes a host from the blocklist.voidremoveHost(java.lang.String hostPortPair)Removes a host from the host list.voidremoveHostWhenNotInUse(java.lang.String hostPortPair)Removes a host from the host list, allowing it some time to be released gracefully if needed.protected booleanshouldExceptionTriggerConnectionSwitch(java.lang.Throwable t)Consults the registered LoadBalanceExceptionChecker if the given exception should trigger a connection fail-over.booleanshouldExceptionTriggerFailover(java.lang.Throwable t)Deprecated.protected voidsyncSessionState(JdbcConnection source, JdbcConnection target, boolean readOnly)Synchronizes session state between two connections, allowing to override the read-only status.Methods inherited from class com.mysql.cj.jdbc.ha.MultiHostConnectionProxy
allowedOnClosedConnection, dealWithInvocationException, getNewJdbcInterfaceProxy, getParentProxy, getProxy, invalidateCurrentConnection, invoke, proxyIfReturnTypeIsJdbcInterface, setProxy
-
Field Details
-
Constructor Details
-
LoadBalancedConnectionProxy
Creates a proxy for java.sql.Connection that routes requests between the hosts in the connection URL.- Parameters:
connectionUrl- The connection URL containing the hosts to load balance.- Throws:
java.sql.SQLException- if an error occurs
-
-
Method Details
-
createProxyInstance
public static LoadBalancedConnection createProxyInstance(ConnectionUrl connectionUrl) throws java.sql.SQLExceptionStatic factory to createLoadBalancedConnectioninstances.- Parameters:
connectionUrl- The connection URL containing the hosts in a load-balance setup.- Returns:
- A
LoadBalancedConnectionproxy. - Throws:
java.sql.SQLException- if an error occurs
-
propagateProxyDown
Propagates the connection proxy down through all live connections.- Overrides:
propagateProxyDownin classMultiHostConnectionProxy- Parameters:
proxyConn- The top level connection in the multi-host connections chain.
-
shouldExceptionTriggerFailover
@Deprecated public boolean shouldExceptionTriggerFailover(java.lang.Throwable t)Deprecated. -
shouldExceptionTriggerConnectionSwitch
protected boolean shouldExceptionTriggerConnectionSwitch(java.lang.Throwable t)Consults the registered LoadBalanceExceptionChecker if the given exception should trigger a connection fail-over.- Specified by:
shouldExceptionTriggerConnectionSwitchin classMultiHostConnectionProxy- Parameters:
t- The Exception instance to check.- Returns:
- true if the given exception should trigger a connection fail-over
-
isSourceConnection
protected boolean isSourceConnection()Always returns 'true' as there are no "sources" and "replicas" in this type of connection.- Specified by:
isSourceConnectionin classMultiHostConnectionProxy- Returns:
- true if current connection is to a source host
-
invalidateConnection
Closes specified connection and removes it from required mappings.- Overrides:
invalidateConnectionin classMultiHostConnectionProxy- Parameters:
conn- connection- Throws:
java.sql.SQLException- if an error occurs
-
pickNewConnection
public void pickNewConnection() throws java.sql.SQLExceptionPicks the "best" connection to use for the next transaction based on the BalanceStrategy in use.- Specified by:
pickNewConnectionin classMultiHostConnectionProxy- Throws:
java.sql.SQLException- if an error occurs
-
createConnectionForHost
Creates a new physical connection for the givenHostInfoand updates required internal mappings and statistics for that connection.- Overrides:
createConnectionForHostin classMultiHostConnectionProxy- Parameters:
hostInfo- The host info instance.- Returns:
- The new Connection instance.
- Throws:
java.sql.SQLException- if an error occurs
-
syncSessionState
protected void syncSessionState(JdbcConnection source, JdbcConnection target, boolean readOnly) throws java.sql.SQLExceptionDescription copied from class:MultiHostConnectionProxySynchronizes session state between two connections, allowing to override the read-only status.- Overrides:
syncSessionStatein classMultiHostConnectionProxy- Parameters:
source- The connection where to get state from.target- The connection where to set state.readOnly- The new read-only status.- Throws:
java.sql.SQLException- if an error occurs
-
createConnectionForHost
public ConnectionImpl createConnectionForHost(java.lang.String hostPortPair) throws java.sql.SQLExceptionCreates 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- The host:port pair identifying the host to connect to.- Returns:
- The new Connection instance.
- Throws:
java.sql.SQLException- if an error occurs
-
doClose
protected void doClose()Closes all live connections.- Specified by:
doClosein classMultiHostConnectionProxy
-
doAbortInternal
protected void doAbortInternal()Aborts all live connections- Specified by:
doAbortInternalin classMultiHostConnectionProxy
-
doAbort
protected void doAbort(java.util.concurrent.Executor executor)Aborts all live connections, using the provided Executor.- Specified by:
doAbortin classMultiHostConnectionProxy- Parameters:
executor- executor
-
invokeMore
public java.lang.Object invokeMore(java.lang.Object proxy, java.lang.reflect.Method method, java.lang.Object[] args) throws java.lang.ThrowableProxies 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[]).- Specified by:
invokeMorein classMultiHostConnectionProxy- Parameters:
proxy- proxy objectmethod- method to invokeargs- method parameters- Returns:
- method result
- Throws:
java.lang.Throwable- if an error occurs
-
doPing
public void doPing() throws java.sql.SQLExceptionPings live connections.- Specified by:
doPingin interfacePingTarget- Throws:
java.sql.SQLException- if an error occurs
-
addToGlobalBlocklist
public void addToGlobalBlocklist(java.lang.String host, long timeout)Adds a host to the blocklist with the given timeout.- Parameters:
host- The host to be blocklisted.timeout- The blocklist timeout for this entry.
-
removeFromGlobalBlocklist
public void removeFromGlobalBlocklist(java.lang.String host)Removes a host from the blocklist.- Parameters:
host- The host to be removed from the blocklist.
-
removeFromGlobalBlacklist
@Deprecated public void removeFromGlobalBlacklist(java.lang.String host)Deprecated.UseremoveFromGlobalBlocklist(String)instead.- Parameters:
host- host
-
addToGlobalBlacklist
@Deprecated public void addToGlobalBlacklist(java.lang.String host, long timeout)Deprecated.UseaddToGlobalBlocklist(String, long)instead.- Parameters:
host- The host to be blocklisted.timeout- The blocklist timeout for this entry.
-
addToGlobalBlocklist
public void addToGlobalBlocklist(java.lang.String host)Adds a host to the blocklist.- Parameters:
host- The host to be blocklisted.
-
addToGlobalBlacklist
@Deprecated public void addToGlobalBlacklist(java.lang.String host)Deprecated.UseaddToGlobalBlocklist(String)instead.- Parameters:
host- The host to be blocklisted.
-
isGlobalBlocklistEnabled
public boolean isGlobalBlocklistEnabled()Checks if host blocklist management was enabled.- Returns:
- true if host blocklist management was enabled
-
isGlobalBlacklistEnabled
@Deprecated public boolean isGlobalBlacklistEnabled()Deprecated.UseisGlobalBlocklistEnabled()instead.- Returns:
- true if host blocklist management was enabled
-
getGlobalBlocklist
public java.util.Map<java.lang.String,java.lang.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:
- A local hosts blocklist.
-
getGlobalBlacklist
@Deprecated public java.util.Map<java.lang.String,java.lang.Long> getGlobalBlacklist()Deprecated.UsegetGlobalBlocklist()instead.- Returns:
- A local hosts blocklist.
-
removeHostWhenNotInUse
public void removeHostWhenNotInUse(java.lang.String hostPortPair) throws java.sql.SQLExceptionRemoves a host from the host list, allowing it some time to be released gracefully if needed.- Parameters:
hostPortPair- The host to be removed.- Throws:
java.sql.SQLException- if an error occurs
-
removeHost
public void removeHost(java.lang.String hostPortPair) throws java.sql.SQLExceptionRemoves a host from the host list.- Parameters:
hostPortPair- The host to be removed.- Throws:
java.sql.SQLException- if an error occurs
-
addHost
public boolean addHost(java.lang.String hostPortPair)Adds a host to the hosts list.- Parameters:
hostPortPair- The host to be added.- Returns:
- true if host was added and false if the host list already contains it
-
inTransaction
public boolean inTransaction() -
getTransactionCount
public long getTransactionCount() -
getActivePhysicalConnectionCount
public long getActivePhysicalConnectionCount() -
getTotalPhysicalConnectionCount
public long getTotalPhysicalConnectionCount() -
getConnectionGroupProxyID
public long getConnectionGroupProxyID() -
getCurrentActiveHost
public java.lang.String getCurrentActiveHost() -
getCurrentTransactionDuration
public long getCurrentTransactionDuration()
-