Search in sources :

Example 16 with DefaultConnection

use of io.mycat.datasource.jdbc.datasource.DefaultConnection in project Mycat2 by MyCATApache.

the class AbstractSQLHandler method executeOnDataNodes.

public void executeOnDataNodes(SQLStatement sqlStatement, JdbcConnectionManager connectionManager, Collection<Partition> partitions, SQLExprTableSource tableSource) {
    HashSet<String> set = new HashSet<>();
    for (Partition partition : partitions) {
        MycatSQLExprTableSourceUtil.setSqlExprTableSource(partition.getSchema(), partition.getTable(), tableSource);
        String sql = sqlStatement.toString();
        try (DefaultConnection connection = connectionManager.getConnection(partition.getTargetName())) {
            DatasourceConfig config = connection.getDataSource().getConfig();
            ConnectionUrlParser connectionUrlParser = ConnectionUrlParser.parseConnectionString(config.getUrl());
            HostInfo hostInfo = connectionUrlParser.getHosts().get(0);
            String ip = hostInfo.getHost();
            String port = hostInfo.getPort() + "";
            if (set.add(ip + ":" + port + ":" + sql)) {
                connection.executeUpdate(sql, false);
            }
        }
    }
}
Also used : DatasourceConfig(io.mycat.config.DatasourceConfig) DefaultConnection(io.mycat.datasource.jdbc.datasource.DefaultConnection) ConnectionUrlParser(com.mysql.cj.conf.ConnectionUrlParser) HostInfo(com.mysql.cj.conf.HostInfo)

Example 17 with DefaultConnection

use of io.mycat.datasource.jdbc.datasource.DefaultConnection in project Mycat2 by MyCATApache.

the class MySQLLogConsumer method accept.

@Override
@SneakyThrows
public void accept(SqlEntry sqlEntry) {
    if (!init) {
        init = true;
        try {
            init();
        } catch (Exception e) {
            LOGGER.error("", e);
        }
    }
    boolean isInRuntime = MetaClusterCurrent.exist(IOExecutor.class) && MetaClusterCurrent.exist(JdbcConnectionManager.class) && MetaClusterCurrent.exist(IOExecutor.class);
    if (isInRuntime) {
        IOExecutor ioExecutor = MetaClusterCurrent.wrapper(IOExecutor.class);
        JdbcConnectionManager jdbcConnectionManager = MetaClusterCurrent.wrapper(JdbcConnectionManager.class);
        MetadataManager metadataManager = MetaClusterCurrent.wrapper(MetadataManager.class);
        ioExecutor.executeBlocking((Handler<Promise<Void>>) event -> {
            try {
                try (DefaultConnection connection = jdbcConnectionManager.getConnection(metadataManager.getPrototype())) {
                    JdbcUtils.execute(connection.getRawConnection(), "INSERT INTO `mycat`.`sql_log` (" + "`instanceId`," + "user," + "connectionId," + "ip," + "port," + "traceId," + "hash," + "sqlType," + "`sql`," + "transactionId," + "sqlTime," + "responseTime," + "affectRow," + "result," + "externalMessage)" + "values(?,?,?,?,?," + "?,?,?,?,?," + "?,?,?,?,?)", Arrays.asList(sqlEntry.getInstanceId(), sqlEntry.getUser(), sqlEntry.getConnectionId(), sqlEntry.getIp(), sqlEntry.getPort(), sqlEntry.getTraceId(), sqlEntry.getHash(), Objects.toString(sqlEntry.getSqlType()), sqlEntry.getSql(), sqlEntry.getTransactionId(), sqlEntry.getSqlTime(), sqlEntry.getResponseTime(), sqlEntry.getAffectRow(), sqlEntry.isResult(), sqlEntry.getExternalMessage()));
                }
            } catch (Exception e) {
                LOGGER.info(" warning sql:{} , info:{}", sqlEntry.getSql(), sqlEntry);
                LOGGER.error("", e);
            } finally {
                event.tryComplete();
            }
        });
    }
}
Also used : MetadataManager(io.mycat.MetadataManager) SqlEntry(io.mycat.monitor.SqlEntry) java.util(java.util) Logger(org.slf4j.Logger) Connection(java.sql.Connection) MetaClusterCurrent(io.mycat.MetaClusterCurrent) SneakyThrows(lombok.SneakyThrows) Promise(io.vertx.core.Promise) LoggerFactory(org.slf4j.LoggerFactory) DefaultConnection(io.mycat.datasource.jdbc.datasource.DefaultConnection) IOExecutor(io.mycat.IOExecutor) Consumer(java.util.function.Consumer) SQLException(java.sql.SQLException) JdbcConnectionManager(io.mycat.datasource.jdbc.datasource.JdbcConnectionManager) JdbcUtils(com.alibaba.druid.util.JdbcUtils) Handler(io.vertx.core.Handler) Promise(io.vertx.core.Promise) MetadataManager(io.mycat.MetadataManager) DefaultConnection(io.mycat.datasource.jdbc.datasource.DefaultConnection) IOExecutor(io.mycat.IOExecutor) JdbcConnectionManager(io.mycat.datasource.jdbc.datasource.JdbcConnectionManager) SQLException(java.sql.SQLException) SneakyThrows(lombok.SneakyThrows)

Example 18 with DefaultConnection

use of io.mycat.datasource.jdbc.datasource.DefaultConnection in project Mycat2 by MyCATApache.

the class JdbcDatasourcePoolImpl method getConnection.

@Override
public Future<NewMycatConnection> getConnection() {
    try {
        JdbcConnectionManager jdbcConnectionManager = MetaClusterCurrent.wrapper(JdbcConnectionManager.class);
        DefaultConnection defaultConnection = jdbcConnectionManager.getConnection(targetName);
        DatabaseInstanceEntry stat = DatabaseInstanceEntry.stat(targetName);
        stat.plusCon();
        stat.plusQps();
        NewMycatConnectionImpl newMycatConnection = new NewMycatConnectionImpl(targetName, defaultConnection.getRawConnection()) {

            long start;

            final AtomicBoolean closeFlag = new AtomicBoolean(false);

            @Override
            public void onSend() {
                start = System.currentTimeMillis();
            }

            @Override
            public void onRev() {
                long end = System.currentTimeMillis();
                InstanceMonitor.plusPrt(end - start);
            }

            @Override
            public Future<Void> close() {
                if (closeFlag.compareAndSet(false, true)) {
                    stat.decCon();
                    defaultConnection.close();
                }
                return Future.succeededFuture();
            }

            @Override
            public void abandonConnection() {
                if (closeFlag.compareAndSet(false, true)) {
                    stat.decCon();
                    Connection rawConnection = defaultConnection.getRawConnection();
                    if (rawConnection instanceof DruidPooledConnection) {
                        DruidPooledConnection connection = (DruidPooledConnection) rawConnection;
                        connection.abandond();
                    }
                    defaultConnection.close();
                }
            }
        };
        return Future.succeededFuture(new ThreadMycatConnectionImplWrapper(stat, newMycatConnection));
    } catch (Throwable throwable) {
        return Future.failedFuture(throwable);
    }
}
Also used : DatabaseInstanceEntry(io.mycat.monitor.DatabaseInstanceEntry) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DefaultConnection(io.mycat.datasource.jdbc.datasource.DefaultConnection) DruidPooledConnection(com.alibaba.druid.pool.DruidPooledConnection) NewMycatConnectionImpl(io.mycat.newquery.NewMycatConnectionImpl) Connection(java.sql.Connection) NewMycatConnection(io.mycat.newquery.NewMycatConnection) DefaultConnection(io.mycat.datasource.jdbc.datasource.DefaultConnection) DruidPooledConnection(com.alibaba.druid.pool.DruidPooledConnection) JdbcConnectionManager(io.mycat.datasource.jdbc.datasource.JdbcConnectionManager) ThreadMycatConnectionImplWrapper(io.mycat.monitor.ThreadMycatConnectionImplWrapper)

Example 19 with DefaultConnection

use of io.mycat.datasource.jdbc.datasource.DefaultConnection in project Mycat2 by MyCATApache.

the class StatisticCenter method init.

@SneakyThrows
public void init() {
    if (init) {
        return;
    }
    init = true;
    JdbcConnectionManager jdbcConnectionManager = MetaClusterCurrent.wrapper(JdbcConnectionManager.class);
    try (DefaultConnection prototype = jdbcConnectionManager.getConnection(MetadataManager.getPrototype())) {
        Connection rawConnection = prototype.getRawConnection();
        JdbcUtils.execute(rawConnection, "CREATE TABLE IF NOT EXISTS mycat.`analyze_table` (\n" + "  `table_rows` bigint(20) NOT NULL,\n" + "  `name` varchar(64) NOT NULL\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
        List<Map<String, Object>> maps = JdbcUtils.executeQuery(rawConnection, "select table_rows as `table_rows`,name from mycat.`analyze_table`", Collections.emptyList());
        for (Map<String, Object> map : maps) {
            Number table_rows = (Number) map.get("table_rows");
            String name = (String) map.get("name");
            String[] strings = name.split("_");
            StatisticObject statisticObject = new StatisticObject();
            statisticObject.setRowCount(table_rows.doubleValue());
            statisticMap.put(Key.of(strings[0], strings[1]), statisticObject);
        }
    }
}
Also used : DefaultConnection(io.mycat.datasource.jdbc.datasource.DefaultConnection) Connection(java.sql.Connection) DefaultConnection(io.mycat.datasource.jdbc.datasource.DefaultConnection) JdbcConnectionManager(io.mycat.datasource.jdbc.datasource.JdbcConnectionManager) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 20 with DefaultConnection

use of io.mycat.datasource.jdbc.datasource.DefaultConnection in project Mycat2 by MyCATApache.

the class DropDatabaseSQLHandler method onPhysics.

protected void onPhysics(String name) {
    MetadataManager metadataManager = MetaClusterCurrent.wrapper(MetadataManager.class);
    JdbcConnectionManager jdbcConnectionManager = MetaClusterCurrent.wrapper(JdbcConnectionManager.class);
    try (DefaultConnection connection = jdbcConnectionManager.getConnection(metadataManager.getPrototype())) {
        connection.executeUpdate(String.format("DROP DATABASE IF EXISTS %s;", name), false);
    } catch (Throwable t) {
        LOGGER.warn("", t);
    }
}
Also used : MetadataManager(io.mycat.MetadataManager) DefaultConnection(io.mycat.datasource.jdbc.datasource.DefaultConnection) JdbcConnectionManager(io.mycat.datasource.jdbc.datasource.JdbcConnectionManager)

Aggregations

DefaultConnection (io.mycat.datasource.jdbc.datasource.DefaultConnection)53 JdbcConnectionManager (io.mycat.datasource.jdbc.datasource.JdbcConnectionManager)39 SneakyThrows (lombok.SneakyThrows)23 Connection (java.sql.Connection)20 MetadataManager (io.mycat.MetadataManager)6 java.util (java.util)6 SQLException (java.sql.SQLException)5 Statement (java.sql.Statement)5 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 Collectors (java.util.stream.Collectors)5 SQLStatement (com.alibaba.druid.sql.ast.SQLStatement)4 SQLIdentifierExpr (com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr)4 RowBaseIterator (io.mycat.api.collector.RowBaseIterator)4 CopyMycatRowMetaData (io.mycat.beans.mycat.CopyMycatRowMetaData)4 ReplicaSelectorManager (io.mycat.replica.ReplicaSelectorManager)4 NameMap (io.mycat.util.NameMap)4 NotNull (org.jetbrains.annotations.NotNull)4 SQLUtils (com.alibaba.druid.sql.SQLUtils)3 SQLPropertyExpr (com.alibaba.druid.sql.ast.expr.SQLPropertyExpr)3 SQLExprTableSource (com.alibaba.druid.sql.ast.statement.SQLExprTableSource)3