com.mysql.cj.jdbc.ha.LoadBalancedConnectionProxy Java Examples

The following examples show how to use com.mysql.cj.jdbc.ha.LoadBalancedConnectionProxy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConnectionGroup.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public long registerConnectionProxy(LoadBalancedConnectionProxy proxy, List<String> localHostList) {
    long currentConnectionId;

    synchronized (this) {
        if (!this.isInitialized) {
            this.hostList.addAll(localHostList);
            this.isInitialized = true;
            this.activeHosts = localHostList.size();
        }
        currentConnectionId = ++this.connections;
        this.connectionProxies.put(Long.valueOf(currentConnectionId), proxy);
    }
    this.activeConnections++;

    return currentConnectionId;

}
 
Example #2
Source File: ConnectionGroup.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Add the given host (host:port pair) to this Connection Group and, consequently, to all the load-balanced connections it holds.
 * 
 * @param hostPortPair
 *            The host:port pair to add.
 * @param forExisting
 *            Whether affects existing load-balanced connections or only new ones.
 */
public void addHost(String hostPortPair, boolean forExisting) {
    synchronized (this) {
        if (this.hostList.add(hostPortPair)) {
            this.activeHosts++;
        }
    }
    // all new connections will have this host
    if (!forExisting) {
        return;
    }

    // make a local copy to keep synchronization overhead to minimum
    Map<Long, LoadBalancedConnectionProxy> proxyMap = new HashMap<>();
    synchronized (this.connectionProxies) {
        proxyMap.putAll(this.connectionProxies);
    }

    for (LoadBalancedConnectionProxy proxy : proxyMap.values()) {
        proxy.addHost(hostPortPair);
    }
}
 
Example #3
Source File: ConnectionGroup.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Add the given host (host:port pair) to this Connection Group and, consequently, to all the load-balanced connections it holds.
 * 
 * @param hostPortPair
 *            The host:port pair to add.
 * @param forExisting
 *            Whether affects existing load-balanced connections or only new ones.
 */
public void addHost(String hostPortPair, boolean forExisting) {
    synchronized (this) {
        if (this.hostList.add(hostPortPair)) {
            this.activeHosts++;
        }
    }
    // all new connections will have this host
    if (!forExisting) {
        return;
    }

    // make a local copy to keep synchronization overhead to minimum
    Map<Long, LoadBalancedConnectionProxy> proxyMap = new HashMap<>();
    synchronized (this.connectionProxies) {
        proxyMap.putAll(this.connectionProxies);
    }

    for (LoadBalancedConnectionProxy proxy : proxyMap.values()) {
        proxy.addHost(hostPortPair);
    }
}
 
Example #4
Source File: ConnectionGroup.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
public long registerConnectionProxy(LoadBalancedConnectionProxy proxy, List<String> localHostList) {
    long currentConnectionId;

    synchronized (this) {
        if (!this.isInitialized) {
            this.hostList.addAll(localHostList);
            this.isInitialized = true;
            this.activeHosts = localHostList.size();
        }
        currentConnectionId = ++this.connections;
        this.connectionProxies.put(Long.valueOf(currentConnectionId), proxy);
    }
    this.activeConnections++;

    return currentConnectionId;

}
 
Example #5
Source File: ConnectionGroup.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public long getActivePhysicalConnectionCount() {
    long result = 0;
    Map<Long, LoadBalancedConnectionProxy> proxyMap = new HashMap<>();
    synchronized (this.connectionProxies) {
        proxyMap.putAll(this.connectionProxies);
    }
    for (LoadBalancedConnectionProxy proxy : proxyMap.values()) {
        result += proxy.getActivePhysicalConnectionCount();
    }
    return result;
}
 
Example #6
Source File: ConnectionGroup.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Remove the given host (host:port pair) from this Connection Group and, consequently, from all the load-balanced connections it holds.
 * 
 * @param hostPortPair
 *            The host:port pair to remove.
 * @param removeExisting
 *            Whether affects existing load-balanced connections or only new ones.
 * @param waitForGracefulFailover
 *            If true instructs the load-balanced connections to fail-over the underlying active connection before removing this host, otherwise remove
 *            immediately.
 * @throws SQLException
 *             if a database access error occurs
 */
public synchronized void removeHost(String hostPortPair, boolean removeExisting, boolean waitForGracefulFailover) throws SQLException {
    if (this.activeHosts == 1) {
        throw SQLError.createSQLException(Messages.getString("ConnectionGroup.0"), null);
    }

    if (this.hostList.remove(hostPortPair)) {
        this.activeHosts--;
    } else {
        throw SQLError.createSQLException(Messages.getString("ConnectionGroup.1", new Object[] { hostPortPair }), null);
    }

    if (removeExisting) {
        // make a local copy to keep synchronization overhead to minimum
        Map<Long, LoadBalancedConnectionProxy> proxyMap = new HashMap<>();
        synchronized (this.connectionProxies) {
            proxyMap.putAll(this.connectionProxies);
        }

        for (LoadBalancedConnectionProxy proxy : proxyMap.values()) {
            if (waitForGracefulFailover) {
                proxy.removeHostWhenNotInUse(hostPortPair);
            } else {
                proxy.removeHost(hostPortPair);
            }
        }
    }
    this.closedHosts.add(hostPortPair);
}
 
Example #7
Source File: ConnectionGroup.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
public void closeConnectionProxy(LoadBalancedConnectionProxy proxy) {
    this.activeConnections--;
    this.connectionProxies.remove(Long.valueOf(proxy.getConnectionGroupProxyID()));
    this.closedProxyTotalPhysicalConnections += proxy.getTotalPhysicalConnectionCount();
    this.closedProxyTotalTransactions += proxy.getTransactionCount();

}
 
Example #8
Source File: ConnectionGroup.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
public long getTotalTransactionCount() {
    // need to account for closed connection proxies
    long transactions = this.closedProxyTotalTransactions;
    Map<Long, LoadBalancedConnectionProxy> proxyMap = new HashMap<>();
    synchronized (this.connectionProxies) {
        proxyMap.putAll(this.connectionProxies);
    }
    for (LoadBalancedConnectionProxy proxy : proxyMap.values()) {
        transactions += proxy.getTransactionCount();
    }
    return transactions;
}
 
Example #9
Source File: ConnectionGroup.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
public long getTotalPhysicalConnectionCount() {
    long allConnections = this.closedProxyTotalPhysicalConnections;
    Map<Long, LoadBalancedConnectionProxy> proxyMap = new HashMap<>();
    synchronized (this.connectionProxies) {
        proxyMap.putAll(this.connectionProxies);
    }
    for (LoadBalancedConnectionProxy proxy : proxyMap.values()) {
        allConnections += proxy.getTotalPhysicalConnectionCount();
    }
    return allConnections;
}
 
Example #10
Source File: ConnectionGroup.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
public long getActivePhysicalConnectionCount() {
    long result = 0;
    Map<Long, LoadBalancedConnectionProxy> proxyMap = new HashMap<>();
    synchronized (this.connectionProxies) {
        proxyMap.putAll(this.connectionProxies);
    }
    for (LoadBalancedConnectionProxy proxy : proxyMap.values()) {
        result += proxy.getActivePhysicalConnectionCount();
    }
    return result;
}
 
Example #11
Source File: NonRegisteringDriver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Try to make a database connection to the given URL. The driver should return "null" if it realizes it is the wrong kind of driver to connect to the given
 * URL. This will be common, as when the JDBC driverManager is asked to connect to a given URL, it passes the URL to each loaded driver in turn.
 * 
 * <p>
 * The driver should raise an SQLException if the URL is null or if it is the right driver to connect to the given URL, but has trouble connecting to the
 * database.
 * </p>
 * 
 * <p>
 * The java.util.Properties argument can be used to pass arbitrary string tag/value pairs as connection arguments. These properties take precedence over any
 * properties sent in the URL.
 * </p>
 * 
 * <p>
 * MySQL protocol takes the form:
 * 
 * <PRE>
 * jdbc:mysql://host:port/database
 * </PRE>
 * 
 * </p>
 * 
 * @param url
 *            the URL of the database to connect to
 * @param info
 *            a list of arbitrary tag/value pairs as connection arguments
 * 
 * @return a connection to the URL or null if it isn't us
 * 
 * @exception SQLException
 *                if a database access error occurs or the url is {@code null}
 * 
 * @see java.sql.Driver#connect
 */
public java.sql.Connection connect(String url, Properties info) throws SQLException {

    try {
        ConnectionUrl conStr = ConnectionUrl.getConnectionUrlInstance(url, info);
        if (conStr.getType() == null) {
            /*
             * According to JDBC spec:
             * The driver should return "null" if it realizes it is the wrong kind of driver to connect to the given URL. This will be common, as when the
             * JDBC driver manager is asked to connect to a given URL it passes the URL to each loaded driver in turn.
             */
            return null;
        }

        switch (conStr.getType()) {
            case LOADBALANCE_CONNECTION:
                return LoadBalancedConnectionProxy.createProxyInstance((LoadbalanceConnectionUrl) conStr);

            case FAILOVER_CONNECTION:
                return FailoverConnectionProxy.createProxyInstance(conStr);

            case REPLICATION_CONNECTION:
                return ReplicationConnectionProxy.createProxyInstance((ReplicationConnectionUrl) conStr);

            case XDEVAPI_SESSION:
                // TODO test it
                //return new XJdbcConnection(conStr.getProperties());

            default:
                return com.mysql.cj.jdbc.ConnectionImpl.getInstance(conStr.getMainHost());

        }

    } catch (CJException ex) {
        throw ExceptionFactory.createException(UnableToConnectException.class,
                Messages.getString("NonRegisteringDriver.17", new Object[] { ex.toString() }), ex);
    }
}
 
Example #12
Source File: ConnectionGroup.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Remove the given host (host:port pair) from this Connection Group and, consequently, from all the load-balanced connections it holds.
 * 
 * @param hostPortPair
 *            The host:port pair to remove.
 * @param removeExisting
 *            Whether affects existing load-balanced connections or only new ones.
 * @param waitForGracefulFailover
 *            If true instructs the load-balanced connections to fail-over the underlying active connection before removing this host, otherwise remove
 *            immediately.
 * @throws SQLException
 */
public synchronized void removeHost(String hostPortPair, boolean removeExisting, boolean waitForGracefulFailover) throws SQLException {
    if (this.activeHosts == 1) {
        throw SQLError.createSQLException(Messages.getString("ConnectionGroup.0"), null);
    }

    if (this.hostList.remove(hostPortPair)) {
        this.activeHosts--;
    } else {
        throw SQLError.createSQLException(Messages.getString("ConnectionGroup.1", new Object[] { hostPortPair }), null);
    }

    if (removeExisting) {
        // make a local copy to keep synchronization overhead to minimum
        Map<Long, LoadBalancedConnectionProxy> proxyMap = new HashMap<>();
        synchronized (this.connectionProxies) {
            proxyMap.putAll(this.connectionProxies);
        }

        for (LoadBalancedConnectionProxy proxy : proxyMap.values()) {
            if (waitForGracefulFailover) {
                proxy.removeHostWhenNotInUse(hostPortPair);
            } else {
                proxy.removeHost(hostPortPair);
            }
        }
    }
    this.closedHosts.add(hostPortPair);
}
 
Example #13
Source File: ConnectionGroup.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void closeConnectionProxy(LoadBalancedConnectionProxy proxy) {
    this.activeConnections--;
    this.connectionProxies.remove(Long.valueOf(proxy.getConnectionGroupProxyID()));
    this.closedProxyTotalPhysicalConnections += proxy.getTotalPhysicalConnectionCount();
    this.closedProxyTotalTransactions += proxy.getTransactionCount();

}
 
Example #14
Source File: ConnectionGroup.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public long getTotalTransactionCount() {
    // need to account for closed connection proxies
    long transactions = this.closedProxyTotalTransactions;
    Map<Long, LoadBalancedConnectionProxy> proxyMap = new HashMap<>();
    synchronized (this.connectionProxies) {
        proxyMap.putAll(this.connectionProxies);
    }
    for (LoadBalancedConnectionProxy proxy : proxyMap.values()) {
        transactions += proxy.getTransactionCount();
    }
    return transactions;
}
 
Example #15
Source File: ConnectionGroup.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public long getTotalPhysicalConnectionCount() {
    long allConnections = this.closedProxyTotalPhysicalConnections;
    Map<Long, LoadBalancedConnectionProxy> proxyMap = new HashMap<>();
    synchronized (this.connectionProxies) {
        proxyMap.putAll(this.connectionProxies);
    }
    for (LoadBalancedConnectionProxy proxy : proxyMap.values()) {
        allConnections += proxy.getTotalPhysicalConnectionCount();
    }
    return allConnections;
}
 
Example #16
Source File: NonRegisteringDriver.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Try to make a database connection to the given URL. The driver should return "null" if it realizes it is the wrong kind of driver to connect to the given
 * URL. This will be common, as when the JDBC driverManager is asked to connect to a given URL, it passes the URL to each loaded driver in turn.
 * 
 * <p>
 * The driver should raise an SQLException if the URL is null or if it is the right driver to connect to the given URL, but has trouble connecting to the
 * database.
 * </p>
 * 
 * <p>
 * The java.util.Properties argument can be used to pass arbitrary string tag/value pairs as connection arguments. These properties take precedence over any
 * properties sent in the URL.
 * </p>
 * 
 * <p>
 * MySQL protocol takes the form: jdbc:mysql://host:port/database
 * </p>
 * 
 * @param url
 *            the URL of the database to connect to
 * @param info
 *            a list of arbitrary tag/value pairs as connection arguments
 * 
 * @return a connection to the URL or null if it isn't us
 * 
 * @exception SQLException
 *                if a database access error occurs or the url is {@code null}
 */
@Override
public java.sql.Connection connect(String url, Properties info) throws SQLException {

    try {
        if (!ConnectionUrl.acceptsUrl(url)) {
            /*
             * According to JDBC spec:
             * The driver should return "null" if it realizes it is the wrong kind of driver to connect to the given URL. This will be common, as when the
             * JDBC driver manager is asked to connect to a given URL it passes the URL to each loaded driver in turn.
             */
            return null;
        }

        ConnectionUrl conStr = ConnectionUrl.getConnectionUrlInstance(url, info);
        switch (conStr.getType()) {
            case SINGLE_CONNECTION:
                return com.mysql.cj.jdbc.ConnectionImpl.getInstance(conStr.getMainHost());

            case LOADBALANCE_CONNECTION:
                return LoadBalancedConnectionProxy.createProxyInstance((LoadbalanceConnectionUrl) conStr);

            case FAILOVER_CONNECTION:
                return FailoverConnectionProxy.createProxyInstance(conStr);

            case REPLICATION_CONNECTION:
                return ReplicationConnectionProxy.createProxyInstance((ReplicationConnectionUrl) conStr);

            default:
                return null;
        }

    } catch (UnsupportedConnectionStringException e) {
        // when Connector/J can't handle this connection string the Driver must return null
        return null;

    } catch (CJException ex) {
        throw ExceptionFactory.createException(UnableToConnectException.class,
                Messages.getString("NonRegisteringDriver.17", new Object[] { ex.toString() }), ex);
    }
}
 
Example #17
Source File: StaticStrategy.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
@Override
public JdbcConnection pickConnection(InvocationHandler proxy, List<String> configuredHosts, Map<String, JdbcConnection> liveConnections,
                                     long[] responseTimes, int numRetries) throws SQLException {
    int numHosts = configuredHosts.size();

    SQLException ex = null;

    List<String> whiteList = new ArrayList<String>(numHosts);
    whiteList.addAll(configuredHosts);

    Map<String, Long> blackList = ((LoadBalancedConnectionProxy) proxy).getGlobalBlacklist();

    whiteList.removeAll(blackList.keySet());

    Map<String, Integer> whiteListMap = this.getArrayIndexMap(whiteList);

    for (int attempts = 0; attempts < numRetries;) {
        if (whiteList.size() == 0) {
            throw SQLError.createSQLException("No hosts configured", null);
        }

        String hostPortSpec = whiteList.get(0);     //Always take the first host

        ConnectionImpl conn = (ConnectionImpl) liveConnections.get(hostPortSpec);

        if (conn == null) {
            try {
                conn = ((LoadBalancedConnectionProxy) proxy).createConnectionForHost(hostPortSpec);
            } catch (SQLException sqlEx) {
                ex = sqlEx;

                if (((LoadBalancedConnectionProxy) proxy).shouldExceptionTriggerFailover(sqlEx)) {

                    Integer whiteListIndex = whiteListMap.get(hostPortSpec);

                    // exclude this host from being picked again
                    if (whiteListIndex != null) {
                        whiteList.remove(whiteListIndex.intValue());
                        whiteListMap = this.getArrayIndexMap(whiteList);
                    }
                    ((LoadBalancedConnectionProxy) proxy).addToGlobalBlacklist(hostPortSpec);

                    if (whiteList.size() == 0) {
                        attempts++;
                        try {
                            Thread.sleep(250);
                        } catch (InterruptedException e) {
                            s_logger.debug("[ignored] interupted while fail over in progres.");
                        }

                        // start fresh
                        whiteListMap = new HashMap<String, Integer>(numHosts);
                        whiteList.addAll(configuredHosts);
                        blackList = ((LoadBalancedConnectionProxy) proxy).getGlobalBlacklist();

                        whiteList.removeAll(blackList.keySet());
                        whiteListMap = this.getArrayIndexMap(whiteList);
                    }

                    continue;
                }

                throw sqlEx;
            }
        }

        return conn;
    }

    if (ex != null) {
        throw ex;
    }

    return null; // we won't get here, compiler can't tell
}