diff --git a/sharding-core/src/main/java/io/shardingsphere/core/optimizer/insert/InsertOptimizeEngine.java b/sharding-core/src/main/java/io/shardingsphere/core/optimizer/insert/InsertOptimizeEngine.java index d086719843c76..180c5f4191640 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/optimizer/insert/InsertOptimizeEngine.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/optimizer/insert/InsertOptimizeEngine.java @@ -81,7 +81,7 @@ public ShardingConditions optimize() { } String expression; Number currentGeneratedKey = generatedKeys.next(); - if (0 == parameters.size()) { + if (parameters.isEmpty()) { if (DefaultKeyword.VALUES.equals(insertValue.getType())) { expression = insertValue.getExpression().substring(0, insertValue.getExpression().lastIndexOf(")")) + ", " + currentGeneratedKey.toString() + ")"; } else { diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutorTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutorTest.java index d4661f6979318..82a9492fce0af 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutorTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutorTest.java @@ -155,7 +155,6 @@ private void setSQLType(final SQLType sqlType) { field.set(actual, sqlType); } - private void setExecuteGroups(final List preparedStatements) { Collection> executeGroups = new LinkedList<>(); List preparedStatementExecuteUnits = new LinkedList<>(); diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java index 76661f4ff9918..e753d3184e55c 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/io/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java @@ -71,7 +71,7 @@ public void assertNoStatement() throws SQLException { } @Test - public void assertExecuteQueryForSinglePreparedStatementSuccess() throws SQLException{ + public void assertExecuteQueryForSinglePreparedStatementSuccess() throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(); ResultSet resultSet = mock(ResultSet.class); when(resultSet.getInt(1)).thenReturn(1); diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/Bootstrap.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/Bootstrap.java index 831597ff5b337..462d9bb61ec5a 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/Bootstrap.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/Bootstrap.java @@ -22,13 +22,13 @@ import io.shardingsphere.core.yaml.other.YamlServerConfiguration; import io.shardingsphere.opentracing.ShardingTracer; import io.shardingsphere.orchestration.internal.OrchestrationFacade; -import io.shardingsphere.shardingproxy.config.ProxyContext; -import io.shardingsphere.shardingproxy.config.yaml.ProxyConfiguration; -import io.shardingsphere.shardingproxy.config.yaml.ProxyYamlConfigurationLoader; +import io.shardingsphere.shardingproxy.config.ShardingConfiguration; +import io.shardingsphere.shardingproxy.config.ShardingConfigurationLoader; import io.shardingsphere.shardingproxy.config.yaml.ProxyYamlRuleConfiguration; import io.shardingsphere.shardingproxy.config.yaml.ProxyYamlServerConfiguration; import io.shardingsphere.shardingproxy.frontend.ShardingProxy; import io.shardingsphere.shardingproxy.listener.ProxyListenerRegister; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import lombok.AccessLevel; import lombok.NoArgsConstructor; @@ -57,13 +57,13 @@ public final class Bootstrap { * @throws IOException IO exception */ public static void main(final String[] args) throws InterruptedException, IOException { - ProxyConfiguration proxyConfig = new ProxyYamlConfigurationLoader().load(); + ShardingConfiguration shardingConfig = new ShardingConfigurationLoader().load(); int port = getPort(args); new ProxyListenerRegister().register(); - if (null == proxyConfig.getServerConfiguration().getOrchestration()) { - startWithoutRegistryCenter(proxyConfig.getServerConfiguration(), proxyConfig.getRuleConfigurationMap(), port); + if (null == shardingConfig.getServerConfiguration().getOrchestration()) { + startWithoutRegistryCenter(shardingConfig.getServerConfiguration(), shardingConfig.getRuleConfigurationMap(), port); } else { - startWithRegistryCenter(proxyConfig.getServerConfiguration(), proxyConfig.getRuleConfigurationMap(), port); + startWithRegistryCenter(shardingConfig.getServerConfiguration(), shardingConfig.getRuleConfigurationMap(), port); } } @@ -80,7 +80,7 @@ private static int getPort(final String[] args) { private static void startWithoutRegistryCenter( final ProxyYamlServerConfiguration serverConfig, final Map ruleConfigs, final int port) throws InterruptedException { - ProxyContext.getInstance().init(getYamlServerConfiguration(serverConfig), getSchemaDataSourceMap(ruleConfigs), getRuleConfiguration(ruleConfigs)); + GlobalRegistry.getInstance().init(getYamlServerConfiguration(serverConfig), getSchemaDataSourceMap(ruleConfigs), getRuleConfiguration(ruleConfigs)); initOpenTracing(); new ShardingProxy().start(port); } @@ -91,7 +91,7 @@ private static void startWithRegistryCenter( if (!ruleConfigs.isEmpty()) { orchestrationFacade.init(getYamlServerConfiguration(serverConfig), getSchemaDataSourceMap(ruleConfigs), getRuleConfiguration(ruleConfigs)); } - ProxyContext.getInstance().init(orchestrationFacade.getConfigService().loadYamlServerConfiguration(), + GlobalRegistry.getInstance().init(orchestrationFacade.getConfigService().loadYamlServerConfiguration(), orchestrationFacade.getConfigService().loadProxyDataSources(), orchestrationFacade.getConfigService().loadProxyConfiguration()); initOpenTracing(); new ShardingProxy().start(port); @@ -99,7 +99,7 @@ private static void startWithRegistryCenter( } private static void initOpenTracing() { - if (ProxyContext.getInstance().isOpenTracingEnable()) { + if (GlobalRegistry.getInstance().isOpenTracingEnable()) { ShardingTracer.init(); } } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/BackendExecutorContext.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/BackendExecutorContext.java index 07ea68cb32d98..e4c41ef16bb41 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/BackendExecutorContext.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/BackendExecutorContext.java @@ -18,7 +18,7 @@ package io.shardingsphere.shardingproxy.backend; import io.shardingsphere.core.executor.ShardingExecuteEngine; -import io.shardingsphere.shardingproxy.config.ProxyContext; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import lombok.Getter; /** @@ -31,7 +31,7 @@ public final class BackendExecutorContext { private static final BackendExecutorContext INSTANCE = new BackendExecutorContext(); @Getter - private final ShardingExecuteEngine executeEngine = new ShardingExecuteEngine(ProxyContext.getInstance().getExecutorSize()); + private final ShardingExecuteEngine executeEngine = new ShardingExecuteEngine(GlobalRegistry.getInstance().getExecutorSize()); /** * Get backend executor context instance. diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/BackendHandlerFactory.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/BackendHandlerFactory.java index 89323ab25adc8..c61179671ee6f 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/BackendHandlerFactory.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/BackendHandlerFactory.java @@ -38,9 +38,9 @@ import io.shardingsphere.shardingproxy.backend.jdbc.wrapper.PreparedStatementExecutorWrapper; import io.shardingsphere.shardingproxy.backend.jdbc.wrapper.StatementExecutorWrapper; import io.shardingsphere.shardingproxy.backend.netty.NettyBackendHandler; -import io.shardingsphere.shardingproxy.config.ProxyContext; -import io.shardingsphere.shardingproxy.config.RuleRegistry; import io.shardingsphere.shardingproxy.frontend.common.FrontendHandler; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; +import io.shardingsphere.shardingproxy.runtime.ShardingSchema; import lombok.AccessLevel; import lombok.NoArgsConstructor; @@ -56,7 +56,7 @@ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class BackendHandlerFactory { - private static final ProxyContext PROXY_CONTEXT = ProxyContext.getInstance(); + private static final GlobalRegistry GLOBAL_REGISTRY = GlobalRegistry.getInstance(); /** * Create new instance of text protocol backend handler. @@ -71,11 +71,11 @@ public final class BackendHandlerFactory { */ public static BackendHandler newTextProtocolInstance( final int connectionId, final int sequenceId, final String sql, final BackendConnection backendConnection, final DatabaseType databaseType, final String schema) { - RuleRegistry ruleRegistry = PROXY_CONTEXT.getRuleRegistry(schema); - backendConnection.setRuleRegistry(ruleRegistry); - return PROXY_CONTEXT.isUseNIO() - ? new NettyBackendHandler(ruleRegistry, connectionId, sequenceId, sql, databaseType) - : new JDBCBackendHandler(ruleRegistry, sql, new JDBCExecuteEngine(backendConnection, new StatementExecutorWrapper(ruleRegistry))); + ShardingSchema shardingSchema = GLOBAL_REGISTRY.getShardingSchema(schema); + backendConnection.setShardingSchema(shardingSchema); + return GLOBAL_REGISTRY.isUseNIO() + ? new NettyBackendHandler(shardingSchema, connectionId, sequenceId, sql, databaseType) + : new JDBCBackendHandler(shardingSchema, sql, new JDBCExecuteEngine(backendConnection, new StatementExecutorWrapper(shardingSchema))); } /** @@ -92,10 +92,10 @@ public static BackendHandler newTextProtocolInstance( */ public static BackendHandler newBinaryProtocolInstance(final int connectionId, final int sequenceId, final String sql, final List parameters, final BackendConnection backendConnection, final DatabaseType databaseType, final String schema) { - RuleRegistry ruleRegistry = PROXY_CONTEXT.getRuleRegistry(schema); - backendConnection.setRuleRegistry(ruleRegistry); - return PROXY_CONTEXT.isUseNIO() ? new NettyBackendHandler(ruleRegistry, connectionId, sequenceId, sql, databaseType) - : new JDBCBackendHandler(ruleRegistry, sql, new JDBCExecuteEngine(backendConnection, new PreparedStatementExecutorWrapper(ruleRegistry, parameters))); + ShardingSchema shardingSchema = GLOBAL_REGISTRY.getShardingSchema(schema); + backendConnection.setShardingSchema(shardingSchema); + return GLOBAL_REGISTRY.isUseNIO() ? new NettyBackendHandler(shardingSchema, connectionId, sequenceId, sql, databaseType) + : new JDBCBackendHandler(shardingSchema, sql, new JDBCExecuteEngine(backendConnection, new PreparedStatementExecutorWrapper(shardingSchema, parameters))); } /** diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaBroadcastBackendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaBroadcastBackendHandler.java index a5dc0bbfc567b..465ee69aeb75e 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaBroadcastBackendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaBroadcastBackendHandler.java @@ -19,7 +19,7 @@ import io.shardingsphere.core.constant.DatabaseType; import io.shardingsphere.shardingproxy.backend.jdbc.connection.BackendConnection; -import io.shardingsphere.shardingproxy.config.ProxyContext; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import io.shardingsphere.shardingproxy.transport.common.packet.DatabasePacket; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.CommandResponsePackets; import io.shardingsphere.shardingproxy.transport.mysql.packet.generic.ErrPacket; @@ -50,7 +50,7 @@ public final class SchemaBroadcastBackendHandler implements BackendHandler { @Override public CommandResponsePackets execute() { List packets = new LinkedList<>(); - for (String schema : ProxyContext.getInstance().getSchemaNames()) { + for (String schema : GlobalRegistry.getInstance().getSchemaNames()) { try (BackendConnection backendConnection = new BackendConnection()) { BackendHandler backendHandler = BackendHandlerFactory.newTextProtocolInstance(connectionId, sequenceId, sql, backendConnection, databaseType, schema); CommandResponsePackets commandResponsePackets = backendHandler.execute(); @@ -63,12 +63,12 @@ public CommandResponsePackets execute() { } @Override - public boolean next() throws SQLException { + public boolean next() { return false; } @Override - public ResultPacket getResultValue() throws SQLException { + public ResultPacket getResultValue() { return null; } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaIgnoreBackendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaIgnoreBackendHandler.java index 7c3b4a75280d6..3f70ebe653ab9 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaIgnoreBackendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaIgnoreBackendHandler.java @@ -22,8 +22,8 @@ import io.shardingsphere.core.parsing.parser.dialect.mysql.statement.ShowDatabasesStatement; import io.shardingsphere.core.parsing.parser.dialect.mysql.statement.UseStatement; import io.shardingsphere.core.parsing.parser.sql.SQLStatement; -import io.shardingsphere.shardingproxy.config.ProxyContext; import io.shardingsphere.shardingproxy.frontend.common.FrontendHandler; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import io.shardingsphere.shardingproxy.transport.mysql.constant.ColumnType; import io.shardingsphere.shardingproxy.transport.mysql.constant.ServerErrorCode; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.CommandResponsePackets; @@ -49,7 +49,7 @@ @RequiredArgsConstructor public final class SchemaIgnoreBackendHandler implements BackendHandler { - private static final ProxyContext PROXY_CONTEXT = ProxyContext.getInstance(); + private static final GlobalRegistry GLOBAL_REGISTRY = GlobalRegistry.getInstance(); private final SQLStatement sqlStatement; @@ -91,7 +91,7 @@ public ResultPacket getResultValue() throws SQLException { private CommandResponsePackets handleUseStatement(final UseStatement useStatement, final FrontendHandler frontendHandler) { String schema = useStatement.getSchema(); - if (!PROXY_CONTEXT.schemaExists(schema)) { + if (!GLOBAL_REGISTRY.schemaExists(schema)) { return new CommandResponsePackets(new ErrPacket(1, ServerErrorCode.ER_BAD_DB_ERROR, schema)); } frontendHandler.setCurrentSchema(schema); @@ -99,7 +99,7 @@ private CommandResponsePackets handleUseStatement(final UseStatement useStatemen } private CommandResponsePackets handleShowDatabasesStatement() { - mergedResult = new ShowDatabasesMergedResult(PROXY_CONTEXT.getSchemaNames()); + mergedResult = new ShowDatabasesMergedResult(GLOBAL_REGISTRY.getSchemaNames()); int sequenceId = 0; FieldCountPacket fieldCountPacket = new FieldCountPacket(++sequenceId, 1); Collection columnDefinition41Packets = new ArrayList<>(1); diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaUnicastBackendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaUnicastBackendHandler.java index 677972d7de5db..5fde352a905a4 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaUnicastBackendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaUnicastBackendHandler.java @@ -19,7 +19,7 @@ import io.shardingsphere.core.constant.DatabaseType; import io.shardingsphere.shardingproxy.backend.jdbc.connection.BackendConnection; -import io.shardingsphere.shardingproxy.config.ProxyContext; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.CommandResponsePackets; import java.sql.SQLException; @@ -34,7 +34,7 @@ public final class SchemaUnicastBackendHandler implements BackendHandler { private final BackendHandler backendHandler; public SchemaUnicastBackendHandler(final int connectionId, final int sequenceId, final String sql, final BackendConnection backendConnection, final DatabaseType databaseType) { - String schema = ProxyContext.getInstance().getSchemaNames().iterator().next(); + String schema = GlobalRegistry.getInstance().getSchemaNames().iterator().next(); backendHandler = BackendHandlerFactory.newTextProtocolInstance(connectionId, sequenceId, sql, backendConnection, databaseType, schema); } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/JDBCBackendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/JDBCBackendHandler.java index 1e406b13ed1b1..b1eb913eaa86f 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/JDBCBackendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/JDBCBackendHandler.java @@ -34,9 +34,9 @@ import io.shardingsphere.shardingproxy.backend.jdbc.execute.response.ExecuteQueryResponse; import io.shardingsphere.shardingproxy.backend.jdbc.execute.response.ExecuteResponse; import io.shardingsphere.shardingproxy.backend.jdbc.execute.response.ExecuteUpdateResponse; -import io.shardingsphere.shardingproxy.config.ProxyContext; -import io.shardingsphere.shardingproxy.config.ProxyTableMetaDataConnectionManager; -import io.shardingsphere.shardingproxy.config.RuleRegistry; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; +import io.shardingsphere.shardingproxy.runtime.ShardingSchema; +import io.shardingsphere.shardingproxy.runtime.metadata.ProxyTableMetaDataConnectionManager; import io.shardingsphere.shardingproxy.transport.mysql.constant.ServerErrorCode; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.CommandResponsePackets; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.ColumnDefinition41Packet; @@ -63,9 +63,9 @@ @RequiredArgsConstructor public final class JDBCBackendHandler extends AbstractBackendHandler { - private static final ProxyContext PROXY_CONTEXT = ProxyContext.getInstance(); + private static final GlobalRegistry GLOBAL_REGISTRY = GlobalRegistry.getInstance(); - private final RuleRegistry ruleRegistry; + private final ShardingSchema shardingSchema; private final String sql; @@ -79,7 +79,7 @@ public final class JDBCBackendHandler extends AbstractBackendHandler { @Override protected CommandResponsePackets execute0() throws SQLException { - return ruleRegistry == null + return shardingSchema == null ? new CommandResponsePackets(new ErrPacket(1, ServerErrorCode.ER_NO_DB_ERROR)) : execute(executeEngine.getJdbcExecutorWrapper().route(sql, DatabaseType.MySQL)); } @@ -94,18 +94,18 @@ private CommandResponsePackets execute(final SQLRouteResult routeResult) throws ServerErrorCode.ER_ERROR_ON_MODIFYING_GTID_EXECUTED_TABLE, sqlStatement.getTables().isSingleTable() ? sqlStatement.getTables().getSingleTableName() : "unknown_table")); } executeResponse = executeEngine.execute(routeResult); - if (!ruleRegistry.isMasterSlaveOnly() && SQLType.DDL == sqlStatement.getType() && !sqlStatement.getTables().isEmpty()) { + if (!shardingSchema.isMasterSlaveOnly() && SQLType.DDL == sqlStatement.getType() && !sqlStatement.getTables().isEmpty()) { String logicTableName = sqlStatement.getTables().getSingleTableName(); // TODO refresh table meta data by SQL parse result - TableMetaDataLoader tableMetaDataLoader = new TableMetaDataLoader(ruleRegistry.getMetaData().getDataSource(), BackendExecutorContext.getInstance().getExecuteEngine(), - new ProxyTableMetaDataConnectionManager(ruleRegistry.getBackendDataSource()), PROXY_CONTEXT.getMaxConnectionsSizePerQuery()); - ruleRegistry.getMetaData().getTable().put(logicTableName, tableMetaDataLoader.load(logicTableName, ruleRegistry.getShardingRule())); + TableMetaDataLoader tableMetaDataLoader = new TableMetaDataLoader(shardingSchema.getMetaData().getDataSource(), BackendExecutorContext.getInstance().getExecuteEngine(), + new ProxyTableMetaDataConnectionManager(shardingSchema.getBackendDataSource()), GLOBAL_REGISTRY.getMaxConnectionsSizePerQuery()); + shardingSchema.getMetaData().getTable().put(logicTableName, tableMetaDataLoader.load(logicTableName, shardingSchema.getShardingRule())); } return merge(sqlStatement); } private boolean isUnsupportedXA(final SQLType sqlType) throws SQLException { - return TransactionType.XA == ProxyContext.getInstance().getTransactionType() && SQLType.DDL == sqlType + return TransactionType.XA == GlobalRegistry.getInstance().getTransactionType() && SQLType.DDL == sqlType && Status.STATUS_NO_TRANSACTION != ShardingTransactionManagerRegistry.getInstance().getShardingTransactionManager(TransactionType.XA).getStatus(); } @@ -114,9 +114,9 @@ private CommandResponsePackets merge(final SQLStatement sqlStatement) throws SQL return ((ExecuteUpdateResponse) executeResponse).merge(); } mergedResult = MergeEngineFactory.newInstance( - ruleRegistry.getShardingRule(), ((ExecuteQueryResponse) executeResponse).getQueryResults(), sqlStatement, ruleRegistry.getMetaData().getTable()).merge(); + shardingSchema.getShardingRule(), ((ExecuteQueryResponse) executeResponse).getQueryResults(), sqlStatement, shardingSchema.getMetaData().getTable()).merge(); if (mergedResult instanceof ShowTablesMergedResult) { - ((ShowTablesMergedResult) mergedResult).resetColumnLabel(ruleRegistry.getSchemaName()); + ((ShowTablesMergedResult) mergedResult).resetColumnLabel(shardingSchema.getName()); setResponseColumnLabelForShowTablesMergedResult(((ExecuteQueryResponse) executeResponse).getQueryResponsePackets()); } QueryResponsePackets result = getQueryResponsePacketsWithoutDerivedColumns(((ExecuteQueryResponse) executeResponse).getQueryResponsePackets()); @@ -139,7 +139,7 @@ private QueryResponsePackets getQueryResponsePacketsWithoutDerivedColumns(final private void setResponseColumnLabelForShowTablesMergedResult(final QueryResponsePackets queryResponsePackets) { for (ColumnDefinition41Packet each : queryResponsePackets.getColumnDefinition41Packets()) { - each.setName("Tables_in_" + ruleRegistry.getSchemaName()); + each.setName("Tables_in_" + shardingSchema.getName()); } } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/connection/BackendConnection.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/connection/BackendConnection.java index ca8116362f2c2..ffcefec3f66a8 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/connection/BackendConnection.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/connection/BackendConnection.java @@ -19,7 +19,7 @@ import io.shardingsphere.core.constant.ConnectionMode; import io.shardingsphere.core.routing.router.masterslave.MasterVisitedManager; -import io.shardingsphere.shardingproxy.config.RuleRegistry; +import io.shardingsphere.shardingproxy.runtime.ShardingSchema; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -44,7 +44,7 @@ public final class BackendConnection implements AutoCloseable { @Getter @Setter - private RuleRegistry ruleRegistry; + private ShardingSchema shardingSchema; private final Collection cachedConnections = new CopyOnWriteArrayList<>(); @@ -71,7 +71,7 @@ public int getConnectionSize() { * @throws SQLException SQL exception */ public List getConnections(final ConnectionMode connectionMode, final String dataSourceName, final int connectionSize) throws SQLException { - List result = ruleRegistry.getBackendDataSource().getConnections(connectionMode, dataSourceName, connectionSize); + List result = shardingSchema.getBackendDataSource().getConnections(connectionMode, dataSourceName, connectionSize); cachedConnections.addAll(result); return result; } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/datasource/JDBCBackendDataSource.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/datasource/JDBCBackendDataSource.java index b2d1bc207ab8f..80e695873816e 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/datasource/JDBCBackendDataSource.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/datasource/JDBCBackendDataSource.java @@ -18,13 +18,11 @@ package io.shardingsphere.shardingproxy.backend.jdbc.datasource; import io.shardingsphere.core.constant.ConnectionMode; -import io.shardingsphere.core.constant.transaction.TransactionType; import io.shardingsphere.core.exception.ShardingException; import io.shardingsphere.core.rule.DataSourceParameter; import io.shardingsphere.shardingproxy.backend.BackendDataSource; -import io.shardingsphere.shardingproxy.config.ProxyContext; -import io.shardingsphere.shardingproxy.config.RuleRegistry; -import lombok.Getter; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; +import io.shardingsphere.shardingproxy.runtime.ShardingSchema; import javax.sql.DataSource; import java.lang.reflect.Method; @@ -44,30 +42,27 @@ * @author zhangliang * @author panjuan */ -@Getter public final class JDBCBackendDataSource implements BackendDataSource, AutoCloseable { - private final RuleRegistry ruleRegistry; + private final ShardingSchema shardingSchema; private final Map dataSourceMap; - public JDBCBackendDataSource(final RuleRegistry ruleRegistry) { - this.ruleRegistry = ruleRegistry; + public JDBCBackendDataSource(final ShardingSchema shardingSchema) { + this.shardingSchema = shardingSchema; dataSourceMap = createDataSourceMap(); } private Map createDataSourceMap() { - TransactionType transactionType = ProxyContext.getInstance().getTransactionType(); - Map dataSourceParameters = ruleRegistry.getDataSources(); - // TODO getCircuitDataSourceMap if RuleRegistry.getInstance().getCircuitBreakerDataSourceNames().isEmpty() is false - return getNormalDataSourceMap(transactionType, dataSourceParameters); + // TODO getCircuitDataSourceMap if getCircuitBreakerDataSourceNames() is not empty + return getNormalDataSourceMap(shardingSchema.getDataSources()); } - private Map getNormalDataSourceMap(final TransactionType transactionType, final Map dataSourceParameters) { + private Map getNormalDataSourceMap(final Map dataSourceParameters) { Map result = new LinkedHashMap<>(dataSourceParameters.size()); for (Entry entry : dataSourceParameters.entrySet()) { try { - result.put(entry.getKey(), getBackendDataSourceFactory(transactionType).build(entry.getKey(), entry.getValue())); + result.put(entry.getKey(), getBackendDataSourceFactory().build(entry.getKey(), entry.getValue())); // CHECKSTYLE:OFF } catch (final Exception ex) { // CHECKSTYLE:ON @@ -77,8 +72,8 @@ private Map getNormalDataSourceMap(final TransactionType tra return result; } - private JDBCBackendDataSourceFactory getBackendDataSourceFactory(final TransactionType transactionType) { - switch (transactionType) { + private JDBCBackendDataSourceFactory getBackendDataSourceFactory() { + switch (GlobalRegistry.getInstance().getTransactionType()) { case XA: return new JDBCXABackendDataSourceFactory(); default: @@ -121,12 +116,12 @@ public List getConnections(final ConnectionMode connectionMode, fina } private Map getDataSourceMap() { - return ruleRegistry.getDisabledDataSourceNames().isEmpty() ? dataSourceMap : getAvailableDataSourceMap(); + return shardingSchema.getDisabledDataSourceNames().isEmpty() ? dataSourceMap : getAvailableDataSourceMap(); } private Map getAvailableDataSourceMap() { Map result = new LinkedHashMap<>(dataSourceMap); - for (String each : ruleRegistry.getDisabledDataSourceNames()) { + for (String each : shardingSchema.getDisabledDataSourceNames()) { result.remove(each); } return result; diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/datasource/JDBCXABackendDataSourceFactory.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/datasource/JDBCXABackendDataSourceFactory.java index 7978ca719a65e..96b1b59fdf741 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/datasource/JDBCXABackendDataSourceFactory.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/datasource/JDBCXABackendDataSourceFactory.java @@ -21,6 +21,7 @@ import io.shardingsphere.core.rule.DataSourceParameter; import io.shardingsphere.transaction.manager.ShardingTransactionManagerRegistry; import io.shardingsphere.transaction.manager.xa.XATransactionManager; +import lombok.SneakyThrows; import javax.sql.DataSource; import javax.sql.XADataSource; @@ -38,18 +39,17 @@ public final class JDBCXABackendDataSourceFactory implements JDBCBackendDataSour @Override public DataSource build(final String dataSourceName, final DataSourceParameter dataSourceParameter) throws Exception { XATransactionManager xaTransactionManager = (XATransactionManager) ShardingTransactionManagerRegistry.getInstance().getShardingTransactionManager(TransactionType.XA); - Class xaDataSourceClass = loadClass(XA_DRIVER_CLASS_NAME); - return xaTransactionManager.wrapDataSource(xaDataSourceClass.newInstance(), dataSourceName, dataSourceParameter); + return xaTransactionManager.wrapDataSource(newXADriverClass(XA_DRIVER_CLASS_NAME), dataSourceName, dataSourceParameter); } - @SuppressWarnings("unchecked") - private Class loadClass(final String className) throws ClassNotFoundException { - Class result; + @SneakyThrows + private XADataSource newXADriverClass(final String className) { + Class result; try { result = Thread.currentThread().getContextClassLoader().loadClass(className); } catch (final ClassNotFoundException ignored) { result = Class.forName(className); } - return result; + return (XADataSource) result.newInstance(); } } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/execute/JDBCExecuteEngine.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/execute/JDBCExecuteEngine.java index 31d05635794ed..d3708fc714999 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/execute/JDBCExecuteEngine.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/execute/JDBCExecuteEngine.java @@ -45,7 +45,7 @@ import io.shardingsphere.shardingproxy.backend.jdbc.execute.response.unit.ExecuteResponseUnit; import io.shardingsphere.shardingproxy.backend.jdbc.execute.response.unit.ExecuteUpdateResponseUnit; import io.shardingsphere.shardingproxy.backend.jdbc.wrapper.JDBCExecutorWrapper; -import io.shardingsphere.shardingproxy.config.ProxyContext; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import io.shardingsphere.shardingproxy.transport.mysql.constant.ColumnType; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.ColumnDefinition41Packet; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.FieldCountPacket; @@ -96,9 +96,9 @@ public final class JDBCExecuteEngine implements SQLExecuteEngine { public JDBCExecuteEngine(final BackendConnection backendConnection, final JDBCExecutorWrapper jdbcExecutorWrapper) { this.backendConnection = backendConnection; this.jdbcExecutorWrapper = jdbcExecutorWrapper; - int maxConnectionsSizePerQuery = ProxyContext.getInstance().getMaxConnectionsSizePerQuery(); + int maxConnectionsSizePerQuery = GlobalRegistry.getInstance().getMaxConnectionsSizePerQuery(); ShardingExecuteEngine executeEngine = BackendExecutorContext.getInstance().getExecuteEngine(); - sqlExecutePrepareTemplate = TransactionType.XA == ProxyContext.getInstance().getTransactionType() + sqlExecutePrepareTemplate = TransactionType.XA == GlobalRegistry.getInstance().getTransactionType() ? new SQLExecutePrepareTemplate(maxConnectionsSizePerQuery) : new SQLExecutePrepareTemplate(maxConnectionsSizePerQuery, executeEngine); sqlExecuteTemplate = new SQLExecuteTemplate(executeEngine); } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/wrapper/PreparedStatementExecutorWrapper.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/wrapper/PreparedStatementExecutorWrapper.java index 2707fc8534d97..bbbd634b5fc40 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/wrapper/PreparedStatementExecutorWrapper.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/wrapper/PreparedStatementExecutorWrapper.java @@ -25,9 +25,9 @@ import io.shardingsphere.core.routing.SQLRouteResult; import io.shardingsphere.core.routing.SQLUnit; import io.shardingsphere.core.routing.router.masterslave.MasterSlaveRouter; -import io.shardingsphere.shardingproxy.config.ProxyContext; -import io.shardingsphere.shardingproxy.config.RuleRegistry; import io.shardingsphere.shardingproxy.rewrite.MasterSlaveSQLRewriteEngine; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; +import io.shardingsphere.shardingproxy.runtime.ShardingSchema; import lombok.RequiredArgsConstructor; import java.sql.Connection; @@ -45,30 +45,30 @@ @RequiredArgsConstructor public final class PreparedStatementExecutorWrapper implements JDBCExecutorWrapper { - private static final ProxyContext PROXY_CONTEXT = ProxyContext.getInstance(); + private static final GlobalRegistry GLOBAL_REGISTRY = GlobalRegistry.getInstance(); - private final RuleRegistry ruleRegistry; + private final ShardingSchema shardingSchema; private final List parameters; @Override public SQLRouteResult route(final String sql, final DatabaseType databaseType) { - return ruleRegistry.isMasterSlaveOnly() ? doMasterSlaveRoute(sql) : doShardingRoute(sql, databaseType); + return shardingSchema.isMasterSlaveOnly() ? doMasterSlaveRoute(sql) : doShardingRoute(sql, databaseType); } private SQLRouteResult doMasterSlaveRoute(final String sql) { SQLStatement sqlStatement = new SQLJudgeEngine(sql).judge(); - String rewriteSQL = new MasterSlaveSQLRewriteEngine(ruleRegistry.getMasterSlaveRule(), sql, sqlStatement, ruleRegistry.getMetaData()).rewrite(); + String rewriteSQL = new MasterSlaveSQLRewriteEngine(shardingSchema.getMasterSlaveRule(), sql, sqlStatement, shardingSchema.getMetaData()).rewrite(); SQLRouteResult result = new SQLRouteResult(sqlStatement); - for (String each : new MasterSlaveRouter(ruleRegistry.getMasterSlaveRule(), PROXY_CONTEXT.isShowSQL()).route(rewriteSQL)) { + for (String each : new MasterSlaveRouter(shardingSchema.getMasterSlaveRule(), GLOBAL_REGISTRY.isShowSQL()).route(rewriteSQL)) { result.getRouteUnits().add(new RouteUnit(each, new SQLUnit(rewriteSQL, Collections.>emptyList()))); } return result; } private SQLRouteResult doShardingRoute(final String sql, final DatabaseType databaseType) { - return new PreparedStatementRoutingEngine( - sql, ruleRegistry.getShardingRule(), ruleRegistry.getMetaData().getTable(), databaseType, PROXY_CONTEXT.isShowSQL(), ruleRegistry.getMetaData().getDataSource()).route(parameters); + return new PreparedStatementRoutingEngine(sql, + shardingSchema.getShardingRule(), shardingSchema.getMetaData().getTable(), databaseType, GLOBAL_REGISTRY.isShowSQL(), shardingSchema.getMetaData().getDataSource()).route(parameters); } @Override diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/wrapper/StatementExecutorWrapper.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/wrapper/StatementExecutorWrapper.java index b075441948010..1716417c0c53d 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/wrapper/StatementExecutorWrapper.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/wrapper/StatementExecutorWrapper.java @@ -25,9 +25,9 @@ import io.shardingsphere.core.routing.SQLUnit; import io.shardingsphere.core.routing.StatementRoutingEngine; import io.shardingsphere.core.routing.router.masterslave.MasterSlaveRouter; -import io.shardingsphere.shardingproxy.config.ProxyContext; -import io.shardingsphere.shardingproxy.config.RuleRegistry; import io.shardingsphere.shardingproxy.rewrite.MasterSlaveSQLRewriteEngine; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; +import io.shardingsphere.shardingproxy.runtime.ShardingSchema; import lombok.RequiredArgsConstructor; import java.sql.Connection; @@ -44,20 +44,20 @@ @RequiredArgsConstructor public final class StatementExecutorWrapper implements JDBCExecutorWrapper { - private static final ProxyContext PROXY_CONTEXT = ProxyContext.getInstance(); + private static final GlobalRegistry GLOBAL_REGISTRY = GlobalRegistry.getInstance(); - private final RuleRegistry ruleRegistry; + private final ShardingSchema shardingSchema; @Override public SQLRouteResult route(final String sql, final DatabaseType databaseType) { - return ruleRegistry.isMasterSlaveOnly() ? doMasterSlaveRoute(sql) : doShardingRoute(sql, databaseType); + return shardingSchema.isMasterSlaveOnly() ? doMasterSlaveRoute(sql) : doShardingRoute(sql, databaseType); } private SQLRouteResult doMasterSlaveRoute(final String sql) { SQLStatement sqlStatement = new SQLJudgeEngine(sql).judge(); - String rewriteSQL = new MasterSlaveSQLRewriteEngine(ruleRegistry.getMasterSlaveRule(), sql, sqlStatement, ruleRegistry.getMetaData()).rewrite(); + String rewriteSQL = new MasterSlaveSQLRewriteEngine(shardingSchema.getMasterSlaveRule(), sql, sqlStatement, shardingSchema.getMetaData()).rewrite(); SQLRouteResult result = new SQLRouteResult(sqlStatement); - for (String each : new MasterSlaveRouter(ruleRegistry.getMasterSlaveRule(), PROXY_CONTEXT.isShowSQL()).route(rewriteSQL)) { + for (String each : new MasterSlaveRouter(shardingSchema.getMasterSlaveRule(), GLOBAL_REGISTRY.isShowSQL()).route(rewriteSQL)) { result.getRouteUnits().add(new RouteUnit(each, new SQLUnit(rewriteSQL, Collections.>emptyList()))); } return result; @@ -65,7 +65,7 @@ private SQLRouteResult doMasterSlaveRoute(final String sql) { private SQLRouteResult doShardingRoute(final String sql, final DatabaseType databaseType) { StatementRoutingEngine routingEngine = new StatementRoutingEngine( - ruleRegistry.getShardingRule(), ruleRegistry.getMetaData().getTable(), databaseType, PROXY_CONTEXT.isShowSQL(), ruleRegistry.getMetaData().getDataSource()); + shardingSchema.getShardingRule(), shardingSchema.getMetaData().getTable(), databaseType, GLOBAL_REGISTRY.isShowSQL(), shardingSchema.getMetaData().getDataSource()); return routingEngine.route(sql); } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/NettyBackendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/NettyBackendHandler.java index a98130d3eba36..a539d9bf58f63 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/NettyBackendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/NettyBackendHandler.java @@ -38,10 +38,10 @@ import io.shardingsphere.shardingproxy.backend.netty.client.response.mysql.MySQLQueryResult; import io.shardingsphere.shardingproxy.backend.netty.future.FutureRegistry; import io.shardingsphere.shardingproxy.backend.netty.future.SynchronizedFuture; -import io.shardingsphere.shardingproxy.config.ProxyContext; -import io.shardingsphere.shardingproxy.config.ProxyTableMetaDataConnectionManager; -import io.shardingsphere.shardingproxy.config.RuleRegistry; import io.shardingsphere.shardingproxy.runtime.ChannelRegistry; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; +import io.shardingsphere.shardingproxy.runtime.ShardingSchema; +import io.shardingsphere.shardingproxy.runtime.metadata.ProxyTableMetaDataConnectionManager; import io.shardingsphere.shardingproxy.transport.common.packet.DatabasePacket; import io.shardingsphere.shardingproxy.transport.mysql.constant.ColumnType; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.CommandResponsePackets; @@ -74,11 +74,11 @@ @Getter public final class NettyBackendHandler extends AbstractBackendHandler { - private static final ProxyContext PROXY_CONTEXT = ProxyContext.getInstance(); + private static final GlobalRegistry GLOBAL_REGISTRY = GlobalRegistry.getInstance(); private static final BackendNettyClientManager CLIENT_MANAGER = BackendNettyClientManager.getInstance(); - private final RuleRegistry ruleRegistry; + private final ShardingSchema shardingSchema; private final int connectionId; @@ -100,15 +100,15 @@ public final class NettyBackendHandler extends AbstractBackendHandler { @Override protected CommandResponsePackets execute0() throws InterruptedException, ExecutionException, TimeoutException, SQLException { - return ruleRegistry.isMasterSlaveOnly() ? executeForMasterSlave() : executeForSharding(); + return shardingSchema.isMasterSlaveOnly() ? executeForMasterSlave() : executeForSharding(); } private CommandResponsePackets executeForMasterSlave() throws InterruptedException, ExecutionException, TimeoutException { - String dataSourceName = new MasterSlaveRouter(ruleRegistry.getMasterSlaveRule(), PROXY_CONTEXT.isShowSQL()).route(sql).iterator().next(); + String dataSourceName = new MasterSlaveRouter(shardingSchema.getMasterSlaveRule(), GLOBAL_REGISTRY.isShowSQL()).route(sql).iterator().next(); synchronizedFuture = new SynchronizedFuture(1); FutureRegistry.getInstance().put(connectionId, synchronizedFuture); executeSQL(dataSourceName, sql); - List queryResults = synchronizedFuture.get(PROXY_CONTEXT.getBackendNIOConfig().getConnectionTimeoutSeconds(), TimeUnit.SECONDS); + List queryResults = synchronizedFuture.get(GLOBAL_REGISTRY.getBackendNIOConfig().getConnectionTimeoutSeconds(), TimeUnit.SECONDS); FutureRegistry.getInstance().delete(connectionId); List packets = new LinkedList<>(); for (QueryResult each : queryResults) { @@ -119,7 +119,7 @@ private CommandResponsePackets executeForMasterSlave() throws InterruptedExcepti private CommandResponsePackets executeForSharding() throws InterruptedException, ExecutionException, TimeoutException, SQLException { StatementRoutingEngine routingEngine = new StatementRoutingEngine( - ruleRegistry.getShardingRule(), ruleRegistry.getMetaData().getTable(), databaseType, PROXY_CONTEXT.isShowSQL(), ruleRegistry.getMetaData().getDataSource()); + shardingSchema.getShardingRule(), shardingSchema.getMetaData().getTable(), databaseType, GLOBAL_REGISTRY.isShowSQL(), shardingSchema.getMetaData().getDataSource()); SQLRouteResult routeResult = routingEngine.route(sql); if (routeResult.getRouteUnits().isEmpty()) { return new CommandResponsePackets(new OKPacket(1)); @@ -129,7 +129,7 @@ private CommandResponsePackets executeForSharding() throws InterruptedException, for (RouteUnit each : routeResult.getRouteUnits()) { executeSQL(each.getDataSourceName(), each.getSqlUnit().getSql()); } - List queryResults = synchronizedFuture.get(PROXY_CONTEXT.getBackendNIOConfig().getConnectionTimeoutSeconds(), TimeUnit.SECONDS); + List queryResults = synchronizedFuture.get(GLOBAL_REGISTRY.getBackendNIOConfig().getConnectionTimeoutSeconds(), TimeUnit.SECONDS); FutureRegistry.getInstance().delete(connectionId); List packets = new ArrayList<>(queryResults.size()); for (QueryResult each : queryResults) { @@ -154,8 +154,8 @@ private void executeSQL(final String dataSourceName, final String sql) throws In if (!channelMap.containsKey(dataSourceName)) { channelMap.put(dataSourceName, new ArrayList()); } - SimpleChannelPool pool = CLIENT_MANAGER.getBackendNettyClient(ruleRegistry.getSchemaName()).getPoolMap().get(dataSourceName); - Channel channel = pool.acquire().get(PROXY_CONTEXT.getBackendNIOConfig().getConnectionTimeoutSeconds(), TimeUnit.SECONDS); + SimpleChannelPool pool = CLIENT_MANAGER.getBackendNettyClient(shardingSchema.getName()).getPoolMap().get(dataSourceName); + Channel channel = pool.acquire().get(GLOBAL_REGISTRY.getBackendNIOConfig().getConnectionTimeoutSeconds(), TimeUnit.SECONDS); channelMap.get(dataSourceName).add(channel); ChannelRegistry.getInstance().putConnectionId(channel.id().asShortText(), connectionId); channel.writeAndFlush(new ComQueryPacket(sequenceId, sql)); @@ -198,7 +198,7 @@ private CommandResponsePackets mergeDML(final CommandResponsePackets firstPacket private CommandResponsePackets mergeDQLorDAL(final SQLStatement sqlStatement, final List packets, final List queryResults) { try { - mergedResult = MergeEngineFactory.newInstance(ruleRegistry.getShardingRule(), queryResults, sqlStatement, ruleRegistry.getMetaData().getTable()).merge(); + mergedResult = MergeEngineFactory.newInstance(shardingSchema.getShardingRule(), queryResults, sqlStatement, shardingSchema.getMetaData().getTable()).merge(); } catch (final SQLException ex) { return new CommandResponsePackets(new ErrPacket(1, ex)); } @@ -208,9 +208,10 @@ private CommandResponsePackets mergeDQLorDAL(final SQLStatement sqlStatement, fi // TODO :jiaqi use sql packet to refresh meta data // TODO refresh table meta data by SQL parse result private void refreshTableMetaData(final String logicTableName) throws SQLException { - TableMetaDataLoader tableMetaDataLoader = new TableMetaDataLoader(ruleRegistry.getMetaData().getDataSource(), - BackendExecutorContext.getInstance().getExecuteEngine(), new ProxyTableMetaDataConnectionManager(ruleRegistry.getBackendDataSource()), PROXY_CONTEXT.getMaxConnectionsSizePerQuery()); - ruleRegistry.getMetaData().getTable().put(logicTableName, tableMetaDataLoader.load(logicTableName, ruleRegistry.getShardingRule())); + TableMetaDataLoader tableMetaDataLoader = new TableMetaDataLoader( + shardingSchema.getMetaData().getDataSource(), BackendExecutorContext.getInstance().getExecuteEngine(), + new ProxyTableMetaDataConnectionManager(shardingSchema.getBackendDataSource()), GLOBAL_REGISTRY.getMaxConnectionsSizePerQuery()); + shardingSchema.getMetaData().getTable().put(logicTableName, tableMetaDataLoader.load(logicTableName, shardingSchema.getShardingRule())); } @Override @@ -234,7 +235,7 @@ public ResultPacket getResultValue() throws SQLException { private void channelRelease() { for (Entry> entry : channelMap.entrySet()) { for (Channel each : entry.getValue()) { - CLIENT_MANAGER.getBackendNettyClient(ruleRegistry.getSchemaName()).getPoolMap().get(entry.getKey()).release(each); + CLIENT_MANAGER.getBackendNettyClient(shardingSchema.getName()).getPoolMap().get(entry.getKey()).release(each); } } } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/client/BackendNettyClient.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/client/BackendNettyClient.java index 17c1f87aaadfe..a38451056f85b 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/client/BackendNettyClient.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/client/BackendNettyClient.java @@ -32,8 +32,8 @@ import io.netty.channel.pool.SimpleChannelPool; import io.netty.channel.socket.nio.NioSocketChannel; import io.shardingsphere.core.metadata.datasource.DataSourceMetaData; -import io.shardingsphere.shardingproxy.config.ProxyContext; -import io.shardingsphere.shardingproxy.config.RuleRegistry; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; +import io.shardingsphere.shardingproxy.runtime.ShardingSchema; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -54,9 +54,9 @@ public final class BackendNettyClient { private static final int WORKER_MAX_THREADS = Runtime.getRuntime().availableProcessors(); - private static final ProxyContext PROXY_CONTEXT = ProxyContext.getInstance(); + private static final GlobalRegistry GLOBAL_REGISTRY = GlobalRegistry.getInstance(); - private final RuleRegistry ruleRegistry; + private final ShardingSchema shardingSchema; private final int maxConnections; @@ -67,11 +67,10 @@ public final class BackendNettyClient { @Getter private ChannelPoolMap poolMap; - public BackendNettyClient(final RuleRegistry ruleRegistry) { - this.ruleRegistry = ruleRegistry; - maxConnections = PROXY_CONTEXT.getBackendNIOConfig().getMaxConnections(); - connectionTimeoutSeconds = PROXY_CONTEXT.getBackendNIOConfig().getConnectionTimeoutSeconds(); - + public BackendNettyClient(final ShardingSchema shardingSchema) { + this.shardingSchema = shardingSchema; + maxConnections = GLOBAL_REGISTRY.getBackendNIOConfig().getMaxConnections(); + connectionTimeoutSeconds = GLOBAL_REGISTRY.getBackendNIOConfig().getConnectionTimeoutSeconds(); } /** @@ -125,13 +124,13 @@ private void initPoolMap(final Bootstrap bootstrap) throws InterruptedException @Override protected SimpleChannelPool newPool(final String dataSourceName) { - DataSourceMetaData dataSourceMetaData = ruleRegistry.getMetaData().getDataSource().getActualDataSourceMetaData(dataSourceName); + DataSourceMetaData dataSourceMetaData = shardingSchema.getMetaData().getDataSource().getActualDataSourceMetaData(dataSourceName); return new FixedChannelPool( bootstrap.remoteAddress(dataSourceMetaData.getHostName(), dataSourceMetaData.getPort()), - new BackendNettyClientChannelPoolHandler(dataSourceName, ruleRegistry.getSchemaName()), maxConnections); + new BackendNettyClientChannelPoolHandler(dataSourceName, shardingSchema.getName()), maxConnections); } }; - for (String each : ruleRegistry.getDataSources().keySet()) { + for (String each : shardingSchema.getDataSources().keySet()) { SimpleChannelPool pool = poolMap.get(each); Channel[] channels = new Channel[maxConnections]; for (int i = 0; i < maxConnections; i++) { diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/client/BackendNettyClientManager.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/client/BackendNettyClientManager.java index 1b30121f85112..06cbdca192c47 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/client/BackendNettyClientManager.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/client/BackendNettyClientManager.java @@ -17,7 +17,7 @@ package io.shardingsphere.shardingproxy.backend.netty.client; -import io.shardingsphere.shardingproxy.config.ProxyContext; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import lombok.AccessLevel; import lombok.NoArgsConstructor; @@ -34,7 +34,7 @@ public final class BackendNettyClientManager { private static final BackendNettyClientManager INSTANCE = new BackendNettyClientManager(); - private static final ProxyContext PROXY_CONTEXT = ProxyContext.getInstance(); + private static final GlobalRegistry GLOBAL_REGISTRY = GlobalRegistry.getInstance(); private final Map clientMap = new HashMap<>(); @@ -63,8 +63,8 @@ public BackendNettyClient getBackendNettyClient(final String schema) { * @throws InterruptedException interrupted exception */ public void start() throws InterruptedException { - for (String each : PROXY_CONTEXT.getSchemaNames()) { - BackendNettyClient backendNettyClient = new BackendNettyClient(PROXY_CONTEXT.getRuleRegistry(each)); + for (String each : GLOBAL_REGISTRY.getSchemaNames()) { + BackendNettyClient backendNettyClient = new BackendNettyClient(GLOBAL_REGISTRY.getShardingSchema(each)); clientMap.put(each, backendNettyClient); backendNettyClient.start(); } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/client/response/mysql/MySQLResponseHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/client/response/mysql/MySQLResponseHandler.java index 43de55f1361a4..8cedd231ef8d9 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/client/response/mysql/MySQLResponseHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/netty/client/response/mysql/MySQLResponseHandler.java @@ -23,8 +23,8 @@ import io.shardingsphere.core.rule.DataSourceParameter; import io.shardingsphere.shardingproxy.backend.netty.client.response.ResponseHandler; import io.shardingsphere.shardingproxy.backend.netty.future.FutureRegistry; -import io.shardingsphere.shardingproxy.config.ProxyContext; import io.shardingsphere.shardingproxy.runtime.ChannelRegistry; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import io.shardingsphere.shardingproxy.transport.mysql.constant.CapabilityFlag; import io.shardingsphere.shardingproxy.transport.mysql.constant.ServerInfo; import io.shardingsphere.shardingproxy.transport.mysql.packet.MySQLPacketPayload; @@ -53,7 +53,7 @@ @RequiredArgsConstructor public final class MySQLResponseHandler extends ResponseHandler { - private static final ProxyContext PROXY_CONTEXT = ProxyContext.getInstance(); + private static final GlobalRegistry GLOBAL_REGISTRY = GlobalRegistry.getInstance(); private final DataSourceParameter dataSourceParameter; @@ -62,8 +62,8 @@ public final class MySQLResponseHandler extends ResponseHandler { private final Map resultMap; public MySQLResponseHandler(final String dataSourceName, final String schema) { - dataSourceParameter = PROXY_CONTEXT.getRuleRegistry(schema).getDataSources().get(dataSourceName); - dataSourceMetaData = PROXY_CONTEXT.getRuleRegistry(schema).getMetaData().getDataSource().getActualDataSourceMetaData(dataSourceName); + dataSourceParameter = GLOBAL_REGISTRY.getShardingSchema(schema).getDataSources().get(dataSourceName); + dataSourceMetaData = GLOBAL_REGISTRY.getShardingSchema(schema).getMetaData().getDataSource().getActualDataSourceMetaData(dataSourceName); resultMap = new HashMap<>(); } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/yaml/ProxyConfiguration.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/ShardingConfiguration.java similarity index 77% rename from sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/yaml/ProxyConfiguration.java rename to sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/ShardingConfiguration.java index 5ce418ee962a6..46558645d6a75 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/yaml/ProxyConfiguration.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/ShardingConfiguration.java @@ -15,21 +15,23 @@ *

*/ -package io.shardingsphere.shardingproxy.config.yaml; +package io.shardingsphere.shardingproxy.config; +import io.shardingsphere.shardingproxy.config.yaml.ProxyYamlRuleConfiguration; +import io.shardingsphere.shardingproxy.config.yaml.ProxyYamlServerConfiguration; import lombok.Getter; import lombok.RequiredArgsConstructor; import java.util.Map; /** - * Proxy configuration. + * Sharding configuration. * * @author zhangliang */ @RequiredArgsConstructor @Getter -public final class ProxyConfiguration { +public final class ShardingConfiguration { private final ProxyYamlServerConfiguration serverConfiguration; diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/yaml/ProxyYamlConfigurationLoader.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/ShardingConfigurationLoader.java similarity index 88% rename from sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/yaml/ProxyYamlConfigurationLoader.java rename to sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/ShardingConfigurationLoader.java index 6eb6855f44522..c7169d1e5c519 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/yaml/ProxyYamlConfigurationLoader.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/ShardingConfigurationLoader.java @@ -15,11 +15,13 @@ *

*/ -package io.shardingsphere.shardingproxy.config.yaml; +package io.shardingsphere.shardingproxy.config; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Strings; +import io.shardingsphere.shardingproxy.config.yaml.ProxyYamlRuleConfiguration; +import io.shardingsphere.shardingproxy.config.yaml.ProxyYamlServerConfiguration; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; @@ -36,11 +38,11 @@ import java.util.regex.Pattern; /** - * Yaml configuration loader. + * Sharding configuration loader. * * @author chenqingyang */ -public final class ProxyYamlConfigurationLoader { +public final class ShardingConfigurationLoader { private static final String CONFIG_PATH = "/conf/"; @@ -54,10 +56,10 @@ public final class ProxyYamlConfigurationLoader { * @return proxy configuration * @throws IOException IO exception */ - public ProxyConfiguration load() throws IOException { + public ShardingConfiguration load() throws IOException { Collection schemaNames = new HashSet<>(); - ProxyYamlServerConfiguration serverConfig = loadServerConfiguration(new File(ProxyYamlConfigurationLoader.class.getResource(CONFIG_PATH + SERVER_CONFIG_FILE).getFile())); - File configPath = new File(ProxyYamlConfigurationLoader.class.getResource(CONFIG_PATH).getFile()); + ProxyYamlServerConfiguration serverConfig = loadServerConfiguration(new File(ShardingConfigurationLoader.class.getResource(CONFIG_PATH + SERVER_CONFIG_FILE).getFile())); + File configPath = new File(ShardingConfigurationLoader.class.getResource(CONFIG_PATH).getFile()); Collection ruleConfigurations = new LinkedList<>(); for (File each : findRuleConfigurationFiles(configPath)) { Optional ruleConfig = loadRuleConfiguration(each, serverConfig); @@ -71,7 +73,7 @@ public ProxyConfiguration load() throws IOException { for (ProxyYamlRuleConfiguration each : ruleConfigurations) { ruleConfigurationMap.put(each.getSchemaName(), each); } - return new ProxyConfiguration(serverConfig, ruleConfigurationMap); + return new ShardingConfiguration(serverConfig, ruleConfigurationMap); } private ProxyYamlServerConfiguration loadServerConfiguration(final File yamlFile) throws IOException { diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/ShardingProxy.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/ShardingProxy.java index 263635a41a133..7edc83a17f262 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/ShardingProxy.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/ShardingProxy.java @@ -32,8 +32,8 @@ import io.netty.handler.logging.LoggingHandler; import io.shardingsphere.shardingproxy.backend.BackendExecutorContext; import io.shardingsphere.shardingproxy.backend.netty.client.BackendNettyClientManager; -import io.shardingsphere.shardingproxy.config.ProxyContext; import io.shardingsphere.shardingproxy.frontend.common.netty.ServerHandlerInitializer; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; /** * Sharding-Proxy. @@ -44,7 +44,7 @@ */ public final class ShardingProxy { - private static final ProxyContext PROXY_CONTEXT = ProxyContext.getInstance(); + private static final GlobalRegistry GLOBAL_REGISTRY = GlobalRegistry.getInstance(); private final BackendExecutorContext backendExecutorContext = BackendExecutorContext.getInstance(); @@ -55,7 +55,7 @@ public final class ShardingProxy { private EventLoopGroup userGroup; public ShardingProxy() { - PROXY_CONTEXT.initShardingMetaData(backendExecutorContext.getExecuteEngine()); + GLOBAL_REGISTRY.initShardingMetaData(backendExecutorContext.getExecuteEngine()); } /** @@ -66,7 +66,7 @@ public ShardingProxy() { */ public void start(final int port) throws InterruptedException { try { - if (PROXY_CONTEXT.isUseNIO()) { + if (GLOBAL_REGISTRY.isUseNIO()) { BackendNettyClientManager.getInstance().start(); } ServerBootstrap bootstrap = new ServerBootstrap(); @@ -83,7 +83,7 @@ public void start(final int port) throws InterruptedException { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); backendExecutorContext.getExecuteEngine().close(); - if (PROXY_CONTEXT.isUseNIO()) { + if (GLOBAL_REGISTRY.isUseNIO()) { BackendNettyClientManager.getInstance().stop(); } } @@ -99,7 +99,7 @@ private EventLoopGroup createEventLoopGroup() { private void groupsEpoll(final ServerBootstrap bootstrap) { workerGroup = new EpollEventLoopGroup(); - userGroup = new EpollEventLoopGroup(PROXY_CONTEXT.getAcceptorSize()); + userGroup = new EpollEventLoopGroup(GLOBAL_REGISTRY.getAcceptorSize()); bootstrap.group(bossGroup, workerGroup) .channel(EpollServerSocketChannel.class) .option(EpollChannelOption.SO_BACKLOG, 128) @@ -112,7 +112,7 @@ private void groupsEpoll(final ServerBootstrap bootstrap) { private void groupsNio(final ServerBootstrap bootstrap) { workerGroup = new NioEventLoopGroup(); - userGroup = new NioEventLoopGroup(PROXY_CONTEXT.getAcceptorSize()); + userGroup = new NioEventLoopGroup(GLOBAL_REGISTRY.getAcceptorSize()); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 128) diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/common/executor/ExecutorGroup.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/common/executor/ExecutorGroup.java index 733c4c3042e3b..eb8d7f9aef8bb 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/common/executor/ExecutorGroup.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/common/executor/ExecutorGroup.java @@ -20,7 +20,7 @@ import io.netty.channel.ChannelId; import io.netty.channel.EventLoopGroup; import io.shardingsphere.core.constant.transaction.TransactionType; -import io.shardingsphere.shardingproxy.config.ProxyContext; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import lombok.RequiredArgsConstructor; import java.util.concurrent.ExecutorService; @@ -33,7 +33,7 @@ @RequiredArgsConstructor public final class ExecutorGroup { - private static final ProxyContext PROXY_CONTEXT = ProxyContext.getInstance(); + private static final GlobalRegistry GLOBAL_REGISTRY = GlobalRegistry.getInstance(); private final EventLoopGroup eventLoopGroup; @@ -45,6 +45,6 @@ public final class ExecutorGroup { * @return executor service */ public ExecutorService getExecutorService() { - return TransactionType.XA == PROXY_CONTEXT.getTransactionType() ? ChannelThreadExecutorGroup.getInstance().get(channelId) : eventLoopGroup; + return TransactionType.XA == GLOBAL_REGISTRY.getTransactionType() ? ChannelThreadExecutorGroup.getInstance().get(channelId) : eventLoopGroup; } } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/mysql/MySQLFrontendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/mysql/MySQLFrontendHandler.java index eda281ce1a897..5030a77bb21b1 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/mysql/MySQLFrontendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/mysql/MySQLFrontendHandler.java @@ -22,13 +22,11 @@ import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.EventLoopGroup; -import io.shardingsphere.spi.root.RootInvokeHook; -import io.shardingsphere.spi.root.SPIRootInvokeHook; import io.shardingsphere.shardingproxy.backend.jdbc.connection.BackendConnection; -import io.shardingsphere.shardingproxy.config.ProxyContext; import io.shardingsphere.shardingproxy.frontend.common.FrontendHandler; import io.shardingsphere.shardingproxy.frontend.common.executor.ExecutorGroup; import io.shardingsphere.shardingproxy.runtime.ChannelRegistry; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import io.shardingsphere.shardingproxy.transport.common.packet.DatabasePacket; import io.shardingsphere.shardingproxy.transport.mysql.constant.ServerErrorCode; import io.shardingsphere.shardingproxy.transport.mysql.packet.MySQLPacketPayload; @@ -43,6 +41,8 @@ import io.shardingsphere.shardingproxy.transport.mysql.packet.handshake.ConnectionIdGenerator; import io.shardingsphere.shardingproxy.transport.mysql.packet.handshake.HandshakePacket; import io.shardingsphere.shardingproxy.transport.mysql.packet.handshake.HandshakeResponse41Packet; +import io.shardingsphere.spi.root.RootInvokeHook; +import io.shardingsphere.spi.root.SPIRootInvokeHook; import lombok.RequiredArgsConstructor; import java.sql.SQLException; @@ -75,7 +75,7 @@ protected void auth(final ChannelHandlerContext context, final ByteBuf message) try (MySQLPacketPayload payload = new MySQLPacketPayload(message)) { HandshakeResponse41Packet response41 = new HandshakeResponse41Packet(payload); if (authenticationHandler.login(response41.getUsername(), response41.getAuthResponse())) { - if (!Strings.isNullOrEmpty(response41.getDatabase()) && !ProxyContext.getInstance().schemaExists(response41.getDatabase())) { + if (!Strings.isNullOrEmpty(response41.getDatabase()) && !GlobalRegistry.getInstance().schemaExists(response41.getDatabase())) { context.writeAndFlush(new ErrPacket(response41.getSequenceId() + 1, ServerErrorCode.ER_BAD_DB_ERROR, response41.getDatabase())); return; } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/listener/ProxyListenerRegister.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/listener/ProxyListenerRegister.java index 73417c87bc7e1..2c9469b0bcd3d 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/listener/ProxyListenerRegister.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/listener/ProxyListenerRegister.java @@ -18,7 +18,7 @@ package io.shardingsphere.shardingproxy.listener; import io.shardingsphere.core.bootstrap.ShardingBootstrap; -import io.shardingsphere.shardingproxy.config.ProxyContext; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; /** * Listener register for Proxy. @@ -28,13 +28,13 @@ */ public final class ProxyListenerRegister { - private final ProxyContext proxyContext = ProxyContext.getInstance(); + private final GlobalRegistry globalRegistry = GlobalRegistry.getInstance(); /** * Register all listeners. */ public void register() { ShardingBootstrap.init(); - proxyContext.register(); + globalRegistry.register(); } } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/ProxyContext.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java similarity index 85% rename from sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/ProxyContext.java rename to sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java index 30eb5559f653a..df49504b29dc4 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/ProxyContext.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java @@ -15,7 +15,7 @@ *

*/ -package io.shardingsphere.shardingproxy.config; +package io.shardingsphere.shardingproxy.runtime; import com.google.common.base.Strings; import com.google.common.eventbus.Subscribe; @@ -24,13 +24,14 @@ import io.shardingsphere.core.constant.transaction.TransactionType; import io.shardingsphere.core.event.ShardingEventBusInstance; import io.shardingsphere.core.executor.ShardingExecuteEngine; -import io.shardingsphere.core.rule.DataSourceParameter; import io.shardingsphere.core.rule.Authentication; +import io.shardingsphere.core.rule.DataSourceParameter; import io.shardingsphere.core.yaml.YamlRuleConfiguration; import io.shardingsphere.core.yaml.other.YamlServerConfiguration; import io.shardingsphere.orchestration.internal.event.config.ProxyConfigurationEventBusEvent; import io.shardingsphere.orchestration.internal.event.state.CircuitStateEventBusEvent; import io.shardingsphere.orchestration.internal.event.state.ProxyDisabledStateEventBusEvent; +import io.shardingsphere.shardingproxy.runtime.nio.BackendNIOConfiguration; import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; @@ -43,26 +44,24 @@ import java.util.concurrent.ConcurrentHashMap; /** - * Proxy context. + * Global registry. * * @author chenqingyang */ @NoArgsConstructor(access = AccessLevel.PRIVATE) @Getter -public final class ProxyContext { +public final class GlobalRegistry { - private static final ProxyContext INSTANCE = new ProxyContext(); + private static final GlobalRegistry INSTANCE = new GlobalRegistry(); private List schemaNames = new LinkedList<>(); - private Map ruleRegistryMap = new ConcurrentHashMap<>(); + private Map shardingSchemas = new ConcurrentHashMap<>(); private Authentication authentication; private boolean showSQL; - private boolean useNIO; - private int maxConnectionsSizePerQuery; private int acceptorSize; @@ -73,6 +72,8 @@ public final class ProxyContext { private boolean openTracingEnable; + private boolean useNIO; + private BackendNIOConfiguration backendNIOConfig; private boolean isCircuitBreak; @@ -82,7 +83,7 @@ public final class ProxyContext { * * @return instance of proxy context. */ - public static ProxyContext getInstance() { + public static GlobalRegistry getInstance() { return INSTANCE; } @@ -105,7 +106,7 @@ public void init(final YamlServerConfiguration serverConfig, final Map entry : schemaRules.entrySet()) { String schemaName = entry.getKey(); schemaNames.add(schemaName); - ruleRegistryMap.put(schemaName, new RuleRegistry(schemaName, schemaDataSources.get(schemaName), entry.getValue())); + shardingSchemas.put(schemaName, new ShardingSchema(schemaName, schemaDataSources.get(schemaName), entry.getValue())); } } @@ -134,7 +135,7 @@ private void initServerConfiguration(final YamlServerConfiguration serverConfig) * @param executeEngine sharding execute engine */ public void initShardingMetaData(final ShardingExecuteEngine executeEngine) { - for (RuleRegistry each : ruleRegistryMap.values()) { + for (ShardingSchema each : shardingSchemas.values()) { each.initShardingMetaData(executeEngine); } } @@ -150,13 +151,13 @@ public boolean schemaExists(final String schema) { } /** - * Get rule registry of schema. + * Get sharding schema. * - * @param schema schema - * @return rule registry of schema + * @param schemaName schema name + * @return sharding schema */ - public RuleRegistry getRuleRegistry(final String schema) { - return Strings.isNullOrEmpty(schema) ? null : ruleRegistryMap.get(schema); + public ShardingSchema getShardingSchema(final String schemaName) { + return Strings.isNullOrEmpty(schemaName) ? null : shardingSchemas.get(schemaName); } /** @@ -167,13 +168,13 @@ public RuleRegistry getRuleRegistry(final String schema) { @Subscribe public void renew(final ProxyConfigurationEventBusEvent proxyConfigurationEventBusEvent) { initServerConfiguration(proxyConfigurationEventBusEvent.getServerConfiguration()); - for (Entry entry : ruleRegistryMap.entrySet()) { + for (Entry entry : shardingSchemas.entrySet()) { entry.getValue().getBackendDataSource().close(); } - ruleRegistryMap.clear(); + shardingSchemas.clear(); for (Entry> entry : proxyConfigurationEventBusEvent.getSchemaDataSourceMap().entrySet()) { String schemaName = entry.getKey(); - ruleRegistryMap.put(schemaName, new RuleRegistry(schemaName, entry.getValue(), proxyConfigurationEventBusEvent.getSchemaRuleMap().get(schemaName))); + shardingSchemas.put(schemaName, new ShardingSchema(schemaName, entry.getValue(), proxyConfigurationEventBusEvent.getSchemaRuleMap().get(schemaName))); } } @@ -194,7 +195,7 @@ public void renewCircuitBreakerDataSourceNames(final CircuitStateEventBusEvent c */ @Subscribe public void renewDisabledDataSourceNames(final ProxyDisabledStateEventBusEvent disabledStateEventBusEvent) { - for (Entry entry : ruleRegistryMap.entrySet()) { + for (Entry entry : shardingSchemas.entrySet()) { entry.getValue().setDisabledDataSourceNames(disabledStateEventBusEvent.getDisabledSchemaDataSourceMap().get(entry.getKey())); } } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/RuleRegistry.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/ShardingSchema.java similarity index 89% rename from sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/RuleRegistry.java rename to sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/ShardingSchema.java index 37516e37a8645..bbfe3f1fa2ffb 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/RuleRegistry.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/ShardingSchema.java @@ -15,7 +15,7 @@ *

*/ -package io.shardingsphere.shardingproxy.config; +package io.shardingsphere.shardingproxy.runtime; import io.shardingsphere.api.config.ShardingRuleConfiguration; import io.shardingsphere.core.constant.DatabaseType; @@ -26,6 +26,7 @@ import io.shardingsphere.core.rule.ShardingRule; import io.shardingsphere.core.yaml.YamlRuleConfiguration; import io.shardingsphere.shardingproxy.backend.jdbc.datasource.JDBCBackendDataSource; +import io.shardingsphere.shardingproxy.runtime.metadata.ProxyTableMetaDataConnectionManager; import lombok.Getter; import lombok.Setter; @@ -36,7 +37,7 @@ import java.util.Map.Entry; /** - * Sharding rule registry. + * Sharding schema. * * @author zhangliang * @author zhangyonglun @@ -45,9 +46,9 @@ * @author wangkai */ @Getter -public final class RuleRegistry { +public final class ShardingSchema { - private final String schemaName; + private final String name; private final Map dataSources; @@ -62,8 +63,8 @@ public final class RuleRegistry { @Setter private Collection disabledDataSourceNames = new LinkedList<>(); - public RuleRegistry(final String schemaName, final Map dataSources, final YamlRuleConfiguration rule) { - this.schemaName = schemaName; + public ShardingSchema(final String name, final Map dataSources, final YamlRuleConfiguration rule) { + this.name = name; // TODO :jiaqi only use JDBC need connect db via JDBC, netty style should use SQL packet to get metadata this.dataSources = dataSources; shardingRule = new ShardingRule(null == rule.getShardingRule() ? new ShardingRuleConfiguration() : rule.getShardingRule().getShardingRuleConfiguration(), dataSources.keySet()); @@ -78,7 +79,7 @@ public RuleRegistry(final String schemaName, final Map getDataSourceURLs(final Map dataSourceParameters) { diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/ProxyTableMetaDataConnectionManager.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/metadata/ProxyTableMetaDataConnectionManager.java similarity index 95% rename from sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/ProxyTableMetaDataConnectionManager.java rename to sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/metadata/ProxyTableMetaDataConnectionManager.java index 6e05adf36704a..cf1a1c613975f 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/ProxyTableMetaDataConnectionManager.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/metadata/ProxyTableMetaDataConnectionManager.java @@ -15,7 +15,7 @@ *

*/ -package io.shardingsphere.shardingproxy.config; +package io.shardingsphere.shardingproxy.runtime.metadata; import io.shardingsphere.core.metadata.table.executor.TableMetaDataConnectionManager; import io.shardingsphere.shardingproxy.backend.jdbc.datasource.JDBCBackendDataSource; diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/BackendNIOConfiguration.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/nio/BackendNIOConfiguration.java similarity index 94% rename from sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/BackendNIOConfiguration.java rename to sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/nio/BackendNIOConfiguration.java index 2c5d3d3a8cc85..7172dafe87cd2 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/config/BackendNIOConfiguration.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/nio/BackendNIOConfiguration.java @@ -15,7 +15,7 @@ *

*/ -package io.shardingsphere.shardingproxy.config; +package io.shardingsphere.shardingproxy.runtime.nio; import lombok.Getter; import lombok.RequiredArgsConstructor; diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/admin/initdb/ComInitDbPacket.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/admin/initdb/ComInitDbPacket.java index bb1f2b9f5305f..776d972f1a736 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/admin/initdb/ComInitDbPacket.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/admin/initdb/ComInitDbPacket.java @@ -18,8 +18,8 @@ package io.shardingsphere.shardingproxy.transport.mysql.packet.command.admin.initdb; import com.google.common.base.Optional; -import io.shardingsphere.shardingproxy.config.ProxyContext; import io.shardingsphere.shardingproxy.frontend.common.FrontendHandler; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import io.shardingsphere.shardingproxy.transport.mysql.constant.ServerErrorCode; import io.shardingsphere.shardingproxy.transport.mysql.packet.MySQLPacketPayload; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.CommandPacket; @@ -61,7 +61,7 @@ public void write(final MySQLPacketPayload payload) { @Override public Optional execute() { log.debug("Schema name received for Sharding-Proxy: {}", schema); - if (ProxyContext.getInstance().schemaExists(schema)) { + if (GlobalRegistry.getInstance().schemaExists(schema)) { frontendHandler.setCurrentSchema(schema); return Optional.of(new CommandResponsePackets(new OKPacket(getSequenceId() + 1))); } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/ComStmtExecutePacket.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/ComStmtExecutePacket.java index e3acbcdb5c3c9..2787f37a9d63a 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/ComStmtExecutePacket.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/ComStmtExecutePacket.java @@ -24,8 +24,8 @@ import io.shardingsphere.shardingproxy.backend.BackendHandlerFactory; import io.shardingsphere.shardingproxy.backend.ResultPacket; import io.shardingsphere.shardingproxy.backend.jdbc.connection.BackendConnection; -import io.shardingsphere.shardingproxy.config.ProxyContext; import io.shardingsphere.shardingproxy.frontend.common.FrontendHandler; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import io.shardingsphere.shardingproxy.transport.common.packet.DatabasePacket; import io.shardingsphere.shardingproxy.transport.mysql.constant.ColumnType; import io.shardingsphere.shardingproxy.transport.mysql.constant.NewParametersBoundFlag; @@ -139,7 +139,7 @@ public void write(final MySQLPacketPayload payload) { @Override public Optional execute() { log.debug("COM_STMT_EXECUTE received for Sharding-Proxy: {}", statementId); - if (ProxyContext.getInstance().isCircuitBreak()) { + if (GlobalRegistry.getInstance().isCircuitBreak()) { return Optional.of(new CommandResponsePackets(new ErrPacket(1, ServerErrorCode.ER_CIRCUIT_BREAK_MODE))); } return Optional.of(backendHandler.execute()); diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/prepare/ComStmtPreparePacket.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/prepare/ComStmtPreparePacket.java index 33a59c72b3a8b..498e0ff641aa6 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/prepare/ComStmtPreparePacket.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/prepare/ComStmtPreparePacket.java @@ -23,9 +23,9 @@ import io.shardingsphere.core.parsing.parser.sql.SQLStatement; import io.shardingsphere.core.parsing.parser.sql.dml.insert.InsertStatement; import io.shardingsphere.core.parsing.parser.sql.dql.select.SelectStatement; -import io.shardingsphere.shardingproxy.config.ProxyContext; -import io.shardingsphere.shardingproxy.config.RuleRegistry; import io.shardingsphere.shardingproxy.frontend.common.FrontendHandler; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; +import io.shardingsphere.shardingproxy.runtime.ShardingSchema; import io.shardingsphere.shardingproxy.transport.mysql.constant.ColumnType; import io.shardingsphere.shardingproxy.transport.mysql.packet.MySQLPacketPayload; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.CommandPacket; @@ -61,8 +61,8 @@ public ComStmtPreparePacket(final int sequenceId, final MySQLPacketPayload paylo this.sequenceId = sequenceId; this.frontendHandler = frontendHandler; sql = payload.readStringEOF(); - RuleRegistry ruleRegistry = ProxyContext.getInstance().getRuleRegistry(frontendHandler.getCurrentSchema()); - sqlParsingEngine = new SQLParsingEngine(DatabaseType.MySQL, sql, ruleRegistry.getShardingRule(), ruleRegistry.getMetaData().getTable()); + ShardingSchema shardingSchema = GlobalRegistry.getInstance().getShardingSchema(frontendHandler.getCurrentSchema()); + sqlParsingEngine = new SQLParsingEngine(DatabaseType.MySQL, sql, shardingSchema.getShardingRule(), shardingSchema.getMetaData().getTable()); } @Override diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/query/ComQueryPacket.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/query/ComQueryPacket.java index 1a064a627df61..ea5833fba5899 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/query/ComQueryPacket.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/query/ComQueryPacket.java @@ -27,8 +27,8 @@ import io.shardingsphere.shardingproxy.backend.BackendHandlerFactory; import io.shardingsphere.shardingproxy.backend.ResultPacket; import io.shardingsphere.shardingproxy.backend.jdbc.connection.BackendConnection; -import io.shardingsphere.shardingproxy.config.ProxyContext; import io.shardingsphere.shardingproxy.frontend.common.FrontendHandler; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import io.shardingsphere.shardingproxy.transport.common.packet.DatabasePacket; import io.shardingsphere.shardingproxy.transport.mysql.constant.ServerErrorCode; import io.shardingsphere.shardingproxy.transport.mysql.packet.MySQLPacketPayload; @@ -84,14 +84,14 @@ public void write(final MySQLPacketPayload payload) { @Override public Optional execute() throws SQLException { log.debug("COM_QUERY received for Sharding-Proxy: {}", sql); - if (ProxyContext.getInstance().isCircuitBreak()) { + if (GlobalRegistry.getInstance().isCircuitBreak()) { return Optional.of(new CommandResponsePackets(new ErrPacket(1, ServerErrorCode.ER_CIRCUIT_BREAK_MODE))); } Optional operationType = TransactionOperationType.getOperationType(sql); if (!operationType.isPresent()) { return Optional.of(backendHandler.execute()); } - if (TransactionType.XA == ProxyContext.getInstance().getTransactionType() && isInTransaction(operationType.get())) { + if (TransactionType.XA == GlobalRegistry.getInstance().getTransactionType() && isInTransaction(operationType.get())) { ShardingEventBusInstance.getInstance().post(new XATransactionEvent(operationType.get())); } // TODO :zhaojun do not send TCL to backend, send when local transaction ready diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/handshake/AuthenticationHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/handshake/AuthenticationHandler.java index 6f2feca85adf8..fb43ec8c7ca46 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/handshake/AuthenticationHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/handshake/AuthenticationHandler.java @@ -19,7 +19,7 @@ import com.google.common.base.Strings; import io.shardingsphere.core.rule.Authentication; -import io.shardingsphere.shardingproxy.config.ProxyContext; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import lombok.Getter; import org.apache.commons.codec.digest.DigestUtils; @@ -33,7 +33,7 @@ @Getter public final class AuthenticationHandler { - private static final ProxyContext PROXY_CONTEXT = ProxyContext.getInstance(); + private static final GlobalRegistry GLOBAL_REGISTRY = GlobalRegistry.getInstance(); private final AuthPluginData authPluginData = new AuthPluginData(); @@ -45,7 +45,7 @@ public final class AuthenticationHandler { * @return login success or failure */ public boolean login(final String username, final byte[] authResponse) { - Authentication authentication = PROXY_CONTEXT.getAuthentication(); + Authentication authentication = GLOBAL_REGISTRY.getAuthentication(); if (Strings.isNullOrEmpty(authentication.getPassword())) { return authentication.getUsername().equals(username); } diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/config/AllConfigTests.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/config/AllConfigTests.java index 91a619ff64f11..067af63a7cdc6 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/config/AllConfigTests.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/config/AllConfigTests.java @@ -22,6 +22,6 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses(ProxyTableMetaDataConnectionManagerTest.class) +@SuiteClasses(ShardingConfigurationLoaderTest.class) public final class AllConfigTests { } diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/config/ShardingConfigurationLoaderTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/config/ShardingConfigurationLoaderTest.java new file mode 100644 index 0000000000000..80df8e35e1bce --- /dev/null +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/config/ShardingConfigurationLoaderTest.java @@ -0,0 +1,101 @@ +/* + * Copyright 2016-2018 shardingsphere.io. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *

+ */ + +package io.shardingsphere.shardingproxy.config; + +import io.shardingsphere.core.rule.DataSourceParameter; +import io.shardingsphere.core.yaml.masterslave.YamlMasterSlaveRuleConfiguration; +import io.shardingsphere.core.yaml.sharding.YamlShardingRuleConfiguration; +import io.shardingsphere.orchestration.yaml.YamlOrchestrationConfiguration; +import io.shardingsphere.shardingproxy.config.yaml.ProxyYamlRuleConfiguration; +import org.junit.Test; + +import java.io.IOException; +import java.util.Iterator; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +public final class ShardingConfigurationLoaderTest { + + @Test + public void assertLoad() throws IOException { + ShardingConfiguration actual = new ShardingConfigurationLoader().load(); + assertOrchestrationConfiguration(actual.getServerConfiguration().getOrchestration()); + assertThat(actual.getRuleConfigurationMap().size(), is(2)); + assertShardingRuleConfiguration(actual.getRuleConfigurationMap().get("sharding_db")); + assertMasterSlaveRuleConfiguration(actual.getRuleConfigurationMap().get("master_slave_db")); + } + + private void assertOrchestrationConfiguration(final YamlOrchestrationConfiguration actual) { + assertThat(actual.getName(), is("orchestration_ds")); + assertTrue(actual.isOverwrite()); + assertThat(actual.getZookeeper().getNamespace(), is("orchestration")); + assertThat(actual.getZookeeper().getServerLists(), is("localhost:2181")); + assertNull(actual.getEtcd()); + } + + private void assertShardingRuleConfiguration(final ProxyYamlRuleConfiguration actual) { + assertThat(actual.getSchemaName(), is("sharding_db")); + assertThat(actual.getDataSources().size(), is(2)); + assertDataSourceParameter(actual.getDataSources().get("ds_0"), "jdbc:mysql://127.0.0.1:3306/ds_0"); + assertDataSourceParameter(actual.getDataSources().get("ds_1"), "jdbc:mysql://127.0.0.1:3306/ds_1"); + assertShardingRuleConfiguration(actual.getShardingRule()); + assertNull(actual.getMasterSlaveRule()); + } + + private void assertShardingRuleConfiguration(final YamlShardingRuleConfiguration actual) { + assertThat(actual.getTables().size(), is(1)); + assertThat(actual.getTables().get("t_order").getActualDataNodes(), is("ds_${0..1}.t_order_${0..1}")); + assertThat(actual.getTables().get("t_order").getDatabaseStrategy().getInline().getShardingColumn(), is("user_id")); + assertThat(actual.getTables().get("t_order").getDatabaseStrategy().getInline().getAlgorithmExpression(), is("ds_${user_id % 2}")); + assertThat(actual.getTables().get("t_order").getTableStrategy().getInline().getShardingColumn(), is("order_id")); + assertThat(actual.getTables().get("t_order").getTableStrategy().getInline().getAlgorithmExpression(), is("t_order_${order_id % 2}")); + } + + private void assertMasterSlaveRuleConfiguration(final ProxyYamlRuleConfiguration actual) { + assertThat(actual.getSchemaName(), is("master_slave_db")); + assertThat(actual.getDataSources().size(), is(3)); + assertDataSourceParameter(actual.getDataSources().get("master_ds"), "jdbc:mysql://127.0.0.1:3306/master_ds"); + assertDataSourceParameter(actual.getDataSources().get("slave_ds_0"), "jdbc:mysql://127.0.0.1:3306/slave_ds_0"); + assertDataSourceParameter(actual.getDataSources().get("slave_ds_1"), "jdbc:mysql://127.0.0.1:3306/slave_ds_1"); + assertNull(actual.getShardingRule()); + assertMasterSlaveRuleConfiguration(actual.getMasterSlaveRule()); + } + + private void assertMasterSlaveRuleConfiguration(final YamlMasterSlaveRuleConfiguration actual) { + assertThat(actual.getName(), is("ms_ds")); + assertThat(actual.getMasterDataSourceName(), is("master_ds")); + assertThat(actual.getSlaveDataSourceNames().size(), is(2)); + Iterator slaveDataSourceNames = actual.getSlaveDataSourceNames().iterator(); + assertThat(slaveDataSourceNames.next(), is("slave_ds_0")); + assertThat(slaveDataSourceNames.next(), is("slave_ds_1")); + } + + private void assertDataSourceParameter(final DataSourceParameter actual, final String expectedURL) { + assertThat(actual.getUrl(), is(expectedURL)); + assertThat(actual.getUsername(), is("root")); + assertNull(actual.getPassword()); + assertTrue(actual.isAutoCommit()); + assertThat(actual.getConnectionTimeout(), is(30000L)); + assertThat(actual.getIdleTimeout(), is(60000L)); + assertThat(actual.getMaxLifetime(), is(1800000L)); + assertThat(actual.getMaximumPoolSize(), is(50)); + } +} diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/listener/ProxyListenerRegisterTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/listener/ProxyListenerRegisterTest.java index f0ee9c602a7dc..d05781cde042a 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/listener/ProxyListenerRegisterTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/listener/ProxyListenerRegisterTest.java @@ -17,7 +17,7 @@ package io.shardingsphere.shardingproxy.listener; -import io.shardingsphere.shardingproxy.config.ProxyContext; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import lombok.SneakyThrows; import org.junit.Before; import org.junit.Test; @@ -35,19 +35,19 @@ public final class ProxyListenerRegisterTest { private final ProxyListenerRegister proxyListenerRegister = new ProxyListenerRegister(); @Mock - private ProxyContext proxyContext; + private GlobalRegistry globalRegistry; @Before @SneakyThrows public void setUp() { - Field field = ProxyListenerRegister.class.getDeclaredField("proxyContext"); + Field field = ProxyListenerRegister.class.getDeclaredField("globalRegistry"); field.setAccessible(true); - field.set(proxyListenerRegister, proxyContext); + field.set(proxyListenerRegister, globalRegistry); } @Test public void assertRegister() { proxyListenerRegister.register(); - verify(proxyContext).register(); + verify(globalRegistry).register(); } } diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/runtime/AllRuntimeTests.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/runtime/AllRuntimeTests.java index 31a3f411d7f2d..4d9c5e5803b94 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/runtime/AllRuntimeTests.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/runtime/AllRuntimeTests.java @@ -17,11 +17,15 @@ package io.shardingsphere.shardingproxy.runtime; +import io.shardingsphere.shardingproxy.runtime.metadata.ProxyTableMetaDataConnectionManagerTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses(ChannelRegistryTest.class) +@SuiteClasses({ + ProxyTableMetaDataConnectionManagerTest.class, + ChannelRegistryTest.class +}) public final class AllRuntimeTests { } diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/config/ProxyTableMetaDataConnectionManagerTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/runtime/metadata/ProxyTableMetaDataConnectionManagerTest.java similarity index 96% rename from sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/config/ProxyTableMetaDataConnectionManagerTest.java rename to sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/runtime/metadata/ProxyTableMetaDataConnectionManagerTest.java index ba59263c0c8f3..b6be29940ab9a 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/config/ProxyTableMetaDataConnectionManagerTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/runtime/metadata/ProxyTableMetaDataConnectionManagerTest.java @@ -15,7 +15,7 @@ *

*/ -package io.shardingsphere.shardingproxy.config; +package io.shardingsphere.shardingproxy.runtime.metadata; import io.shardingsphere.shardingproxy.backend.jdbc.datasource.JDBCBackendDataSource; import org.junit.Test; diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/CommandPacketFactoryTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/CommandPacketFactoryTest.java index eefe1b00ff6ae..e3118e5d507f5 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/CommandPacketFactoryTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/CommandPacketFactoryTest.java @@ -20,9 +20,9 @@ import io.shardingsphere.core.constant.ShardingConstant; import io.shardingsphere.core.metadata.ShardingMetaData; import io.shardingsphere.shardingproxy.backend.jdbc.connection.BackendConnection; -import io.shardingsphere.shardingproxy.config.ProxyContext; -import io.shardingsphere.shardingproxy.config.RuleRegistry; import io.shardingsphere.shardingproxy.frontend.common.FrontendHandler; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; +import io.shardingsphere.shardingproxy.runtime.ShardingSchema; import io.shardingsphere.shardingproxy.transport.mysql.constant.NewParametersBoundFlag; import io.shardingsphere.shardingproxy.transport.mysql.packet.MySQLPacketPayload; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.admin.UnsupportedCommandPacket; @@ -66,20 +66,20 @@ public final class CommandPacketFactoryTest { @Before public void setUp() { - setProxyContextRuleRegistryMap(); + setShardingSchemas(); setFrontendHandlerSchema(); } @SneakyThrows - private void setProxyContextRuleRegistryMap() { - RuleRegistry ruleRegistry = mock(RuleRegistry.class); + private void setShardingSchemas() { + ShardingSchema shardingSchema = mock(ShardingSchema.class); ShardingMetaData metaData = mock(ShardingMetaData.class); - when(ruleRegistry.getMetaData()).thenReturn(metaData); - Map ruleRegistryMap = new HashMap<>(); - ruleRegistryMap.put(ShardingConstant.LOGIC_SCHEMA_NAME, ruleRegistry); - Field field = ProxyContext.class.getDeclaredField("ruleRegistryMap"); + when(shardingSchema.getMetaData()).thenReturn(metaData); + Map shardingSchemas = new HashMap<>(); + shardingSchemas.put(ShardingConstant.LOGIC_SCHEMA_NAME, shardingSchema); + Field field = GlobalRegistry.class.getDeclaredField("shardingSchemas"); field.setAccessible(true); - field.set(ProxyContext.getInstance(), ruleRegistryMap); + field.set(GlobalRegistry.getInstance(), shardingSchemas); } private void setFrontendHandlerSchema() { diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/admin/initdb/ComInitDbPacketTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/admin/initdb/ComInitDbPacketTest.java index b11cd2f3fd936..20abd352c78d6 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/admin/initdb/ComInitDbPacketTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/admin/initdb/ComInitDbPacketTest.java @@ -19,8 +19,8 @@ import com.google.common.base.Optional; import io.shardingsphere.core.constant.ShardingConstant; -import io.shardingsphere.shardingproxy.config.ProxyContext; import io.shardingsphere.shardingproxy.frontend.common.FrontendHandler; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import io.shardingsphere.shardingproxy.transport.mysql.constant.ServerErrorCode; import io.shardingsphere.shardingproxy.transport.mysql.packet.MySQLPacketPayload; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.CommandPacketType; @@ -58,9 +58,9 @@ public final class ComInitDbPacketTest { public void setUp() { List schemaNames = new ArrayList<>(1); schemaNames.add(ShardingConstant.LOGIC_SCHEMA_NAME); - Field field = ProxyContext.class.getDeclaredField("schemaNames"); + Field field = GlobalRegistry.class.getDeclaredField("schemaNames"); field.setAccessible(true); - field.set(ProxyContext.getInstance(), schemaNames); + field.set(GlobalRegistry.getInstance(), schemaNames); } @Test diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/ComStmtExecutePacketTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/ComStmtExecutePacketTest.java index f59df6e87377c..16dff762068db 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/ComStmtExecutePacketTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/ComStmtExecutePacketTest.java @@ -21,8 +21,8 @@ import io.shardingsphere.shardingproxy.backend.BackendHandler; import io.shardingsphere.shardingproxy.backend.ResultPacket; import io.shardingsphere.shardingproxy.backend.jdbc.connection.BackendConnection; -import io.shardingsphere.shardingproxy.config.ProxyContext; import io.shardingsphere.shardingproxy.frontend.common.FrontendHandler; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import io.shardingsphere.shardingproxy.transport.common.packet.DatabasePacket; import io.shardingsphere.shardingproxy.transport.mysql.constant.ColumnType; import io.shardingsphere.shardingproxy.transport.mysql.packet.MySQLPacketPayload; @@ -64,7 +64,7 @@ public final class ComStmtExecutePacketTest { @Before public void setUp() { - setProxyContextNIOConfig(); + setNIOConfig(); } @Before @@ -74,10 +74,10 @@ public void reset() { } @SneakyThrows - private void setProxyContextNIOConfig() { - Field field = ProxyContext.class.getDeclaredField("useNIO"); + private void setNIOConfig() { + Field field = GlobalRegistry.class.getDeclaredField("useNIO"); field.setAccessible(true); - field.set(ProxyContext.getInstance(), true); + field.set(GlobalRegistry.getInstance(), true); } @Test diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/prepare/ComStmtPreparePacketTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/prepare/ComStmtPreparePacketTest.java index d7fb8235569f5..63cb288bff8bd 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/prepare/ComStmtPreparePacketTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/prepare/ComStmtPreparePacketTest.java @@ -27,9 +27,9 @@ import io.shardingsphere.core.parsing.parser.sql.SQLStatement; import io.shardingsphere.core.parsing.parser.sql.dml.insert.InsertStatement; import io.shardingsphere.core.parsing.parser.sql.dql.select.SelectStatement; -import io.shardingsphere.shardingproxy.config.ProxyContext; -import io.shardingsphere.shardingproxy.config.RuleRegistry; import io.shardingsphere.shardingproxy.frontend.common.FrontendHandler; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; +import io.shardingsphere.shardingproxy.runtime.ShardingSchema; import io.shardingsphere.shardingproxy.transport.common.packet.DatabasePacket; import io.shardingsphere.shardingproxy.transport.mysql.constant.ColumnType; import io.shardingsphere.shardingproxy.transport.mysql.packet.MySQLPacketPayload; @@ -70,7 +70,7 @@ public final class ComStmtPreparePacketTest { @Before public void setUp() { - setProxyContextRuleRegistryMap(); + setShardingSchemaMap(); setFrontendHandlerSchema(); } @@ -81,15 +81,15 @@ public void reset() { } @SneakyThrows - private void setProxyContextRuleRegistryMap() { - RuleRegistry ruleRegistry = mock(RuleRegistry.class); + private void setShardingSchemaMap() { + ShardingSchema shardingSchema = mock(ShardingSchema.class); ShardingMetaData metaData = mock(ShardingMetaData.class); - when(ruleRegistry.getMetaData()).thenReturn(metaData); - Map ruleRegistryMap = new HashMap<>(); - ruleRegistryMap.put(ShardingConstant.LOGIC_SCHEMA_NAME, ruleRegistry); - Field field = ProxyContext.class.getDeclaredField("ruleRegistryMap"); + when(shardingSchema.getMetaData()).thenReturn(metaData); + Map shardingSchemas = new HashMap<>(); + shardingSchemas.put(ShardingConstant.LOGIC_SCHEMA_NAME, shardingSchema); + Field field = GlobalRegistry.class.getDeclaredField("shardingSchemas"); field.setAccessible(true); - field.set(ProxyContext.getInstance(), ruleRegistryMap); + field.set(GlobalRegistry.getInstance(), shardingSchemas); } private void setFrontendHandlerSchema() { diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/query/ComQueryPacketTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/query/ComQueryPacketTest.java index 57236698dec76..1e13a91443e3c 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/query/ComQueryPacketTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/query/ComQueryPacketTest.java @@ -27,9 +27,9 @@ import io.shardingsphere.shardingproxy.backend.BackendHandler; import io.shardingsphere.shardingproxy.backend.ResultPacket; import io.shardingsphere.shardingproxy.backend.jdbc.connection.BackendConnection; -import io.shardingsphere.shardingproxy.config.ProxyContext; -import io.shardingsphere.shardingproxy.config.RuleRegistry; import io.shardingsphere.shardingproxy.frontend.common.FrontendHandler; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; +import io.shardingsphere.shardingproxy.runtime.ShardingSchema; import io.shardingsphere.shardingproxy.transport.common.packet.DatabasePacket; import io.shardingsphere.shardingproxy.transport.mysql.constant.ColumnType; import io.shardingsphere.shardingproxy.transport.mysql.packet.MySQLPacketPayload; @@ -79,8 +79,8 @@ public final class ComQueryPacketTest { @Before public void setUp() { - setProxyContextNIOConfig(); - setProxyContextRuleRegistryMap(); + setNIOConfig(); + setShardingSchemas(); setFrontendHandlerSchema(); listener = new Listener(); listener.setExpected(TransactionOperationType.COMMIT); @@ -94,20 +94,20 @@ public void tearDown() { } @SneakyThrows - private void setProxyContextNIOConfig() { - Field field = ProxyContext.class.getDeclaredField("useNIO"); + private void setNIOConfig() { + Field field = GlobalRegistry.class.getDeclaredField("useNIO"); field.setAccessible(true); - field.set(ProxyContext.getInstance(), true); + field.set(GlobalRegistry.getInstance(), true); } @SneakyThrows - private void setProxyContextRuleRegistryMap() { - RuleRegistry ruleRegistry = mock(RuleRegistry.class); - Map ruleRegistryMap = new HashMap<>(); - ruleRegistryMap.put(ShardingConstant.LOGIC_SCHEMA_NAME, ruleRegistry); - Field field = ProxyContext.class.getDeclaredField("ruleRegistryMap"); + private void setShardingSchemas() { + ShardingSchema shardingSchema = mock(ShardingSchema.class); + Map shardingSchemas = new HashMap<>(); + shardingSchemas.put(ShardingConstant.LOGIC_SCHEMA_NAME, shardingSchema); + Field field = GlobalRegistry.class.getDeclaredField("shardingSchemas"); field.setAccessible(true); - field.set(ProxyContext.getInstance(), ruleRegistryMap); + field.set(GlobalRegistry.getInstance(), shardingSchemas); } private void setFrontendHandlerSchema() { @@ -116,9 +116,9 @@ private void setFrontendHandlerSchema() { @SneakyThrows private void setTransactionType(final TransactionType transactionType) { - Field transactionTypeField = ProxyContext.class.getDeclaredField("transactionType"); + Field transactionTypeField = GlobalRegistry.class.getDeclaredField("transactionType"); transactionTypeField.setAccessible(true); - transactionTypeField.set(ProxyContext.getInstance(), transactionType); + transactionTypeField.set(GlobalRegistry.getInstance(), transactionType); } @Test diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/handshake/AuthenticationHandlerTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/handshake/AuthenticationHandlerTest.java index 307a4c4909a24..ea59fa1b6ccc2 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/handshake/AuthenticationHandlerTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/packet/handshake/AuthenticationHandlerTest.java @@ -19,7 +19,7 @@ import com.google.common.primitives.Bytes; import io.shardingsphere.core.rule.Authentication; -import io.shardingsphere.shardingproxy.config.ProxyContext; +import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import lombok.SneakyThrows; import org.junit.Before; import org.junit.Test; @@ -40,16 +40,16 @@ public final class AuthenticationHandlerTest { @Before public void setUp() { - initAuthenticationForProxyContext(); + initAuthentication(); initAuthPluginDataForAuthenticationHandler(); } @SneakyThrows - private void initAuthenticationForProxyContext() { + private void initAuthentication() { Authentication authentication = new Authentication(); - Field field = ProxyContext.class.getDeclaredField("authentication"); + Field field = GlobalRegistry.class.getDeclaredField("authentication"); field.setAccessible(true); - field.set(ProxyContext.getInstance(), authentication); + field.set(GlobalRegistry.getInstance(), authentication); } @SneakyThrows @@ -62,15 +62,15 @@ private void initAuthPluginDataForAuthenticationHandler() { @Test public void assertLoginWithPassword() { - ProxyContext.getInstance().getAuthentication().setUsername("root"); - ProxyContext.getInstance().getAuthentication().setPassword("root"); + GlobalRegistry.getInstance().getAuthentication().setUsername("root"); + GlobalRegistry.getInstance().getAuthentication().setPassword("root"); byte[] authResponse = {-27, 89, -20, -27, 65, -120, -64, -101, 86, -100, -108, -100, 6, -125, -37, 117, 14, -43, 95, -113}; assertTrue(authenticationHandler.login("root", authResponse)); } @Test public void assertLoginWithoutPassword() { - ProxyContext.getInstance().getAuthentication().setUsername("root"); + GlobalRegistry.getInstance().getAuthentication().setUsername("root"); byte[] authResponse = {-27, 89, -20, -27, 65, -120, -64, -101, 86, -100, -108, -100, 6, -125, -37, 117, 14, -43, 95, -113}; assertTrue(authenticationHandler.login("root", authResponse)); } diff --git a/sharding-proxy/src/test/resources/conf/config-empty.yaml b/sharding-proxy/src/test/resources/conf/config-empty.yaml new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sharding-proxy/src/test/resources/conf/config-master_slave.yaml b/sharding-proxy/src/test/resources/conf/config-master_slave.yaml new file mode 100644 index 0000000000000..0b22709bcb595 --- /dev/null +++ b/sharding-proxy/src/test/resources/conf/config-master_slave.yaml @@ -0,0 +1,37 @@ +schemaName: master_slave_db + +dataSources: + master_ds: + url: jdbc:mysql://127.0.0.1:3306/master_ds + username: root + password: + autoCommit: true + connectionTimeout: 30000 + idleTimeout: 60000 + maxLifetime: 1800000 + maximumPoolSize: 50 + slave_ds_0: + url: jdbc:mysql://127.0.0.1:3306/slave_ds_0 + username: root + password: + autoCommit: true + connectionTimeout: 30000 + idleTimeout: 60000 + maxLifetime: 1800000 + maximumPoolSize: 50 + slave_ds_1: + url: jdbc:mysql://127.0.0.1:3306/slave_ds_1 + username: root + password: + autoCommit: true + connectionTimeout: 30000 + idleTimeout: 60000 + maxLifetime: 1800000 + maximumPoolSize: 50 + +masterSlaveRule: + name: ms_ds + masterDataSourceName: master_ds + slaveDataSourceNames: + - slave_ds_0 + - slave_ds_1 diff --git a/sharding-proxy/src/test/resources/conf/config-sharding.yaml b/sharding-proxy/src/test/resources/conf/config-sharding.yaml new file mode 100644 index 0000000000000..aefe9bda9409b --- /dev/null +++ b/sharding-proxy/src/test/resources/conf/config-sharding.yaml @@ -0,0 +1,34 @@ +schemaName: sharding_db + +dataSources: + ds_0: + url: jdbc:mysql://127.0.0.1:3306/ds_0 + username: root + password: + autoCommit: true + connectionTimeout: 30000 + idleTimeout: 60000 + maxLifetime: 1800000 + maximumPoolSize: 50 + ds_1: + url: jdbc:mysql://127.0.0.1:3306/ds_1 + username: root + password: + autoCommit: true + connectionTimeout: 30000 + idleTimeout: 60000 + maxLifetime: 1800000 + maximumPoolSize: 50 + +shardingRule: + tables: + t_order: + actualDataNodes: ds_${0..1}.t_order_${0..1} + databaseStrategy: + inline: + shardingColumn: user_id + algorithmExpression: ds_${user_id % 2} + tableStrategy: + inline: + shardingColumn: order_id + algorithmExpression: t_order_${order_id % 2} diff --git a/sharding-proxy/src/test/resources/conf/config.yaml b/sharding-proxy/src/test/resources/conf/config.yaml deleted file mode 100644 index af7407d2f6ebd..0000000000000 --- a/sharding-proxy/src/test/resources/conf/config.yaml +++ /dev/null @@ -1,63 +0,0 @@ -dataSources: - ds_0: - url: jdbc:mysql://127.0.0.1:3306/ds_0?serverTimezone=UTC&useSSL=false - username: root - password: - autoCommit: true - connectionTimeout: 30000 - idleTimeout: 60000 - maxLifetime: 1800000 - maximumPoolSize: 65 - ds_1: - url: jdbc:mysql://127.0.0.1:3306/ds_1?serverTimezone=UTC&useSSL=false - username: root - password: - autoCommit: true - connectionTimeout: 30000 - idleTimeout: 60000 - maxLifetime: 1800000 - maximumPoolSize: 65 - -shardingRule: - tables: - t_order: - actualDataNodes: ds_${0..1}.t_order_${0..1} - tableStrategy: - inline: - shardingColumn: order_id - algorithmExpression: t_order_${order_id % 2} - keyGeneratorColumnName: order_id - t_order_item: - actualDataNodes: ds_${0..1}.t_order_item_${0..1} - tableStrategy: - inline: - shardingColumn: order_id - algorithmExpression: t_order_item_${order_id % 2} - bindingTables: - - t_order,t_order_item - defaultDatabaseStrategy: - inline: - shardingColumn: user_id - algorithmExpression: ds_${user_id % 2} - defaultTableStrategy: - none: - defaultKeyGeneratorClassName: io.shardingsphere.core.keygen.DefaultKeyGenerator - - props: - connection.mode: MEMORY_STRICTLY - acceptor.size: 16 - executor.size: 16 - sql.show: false - -orchestration: - name: orchestration_ds - type: SHARDING - overwrite: true - zookeeper: - namespace: orchestration - serverLists: localhost:2181 - -authentication: - username: root - password: root - diff --git a/sharding-proxy/src/test/resources/conf/server.yaml b/sharding-proxy/src/test/resources/conf/server.yaml new file mode 100644 index 0000000000000..cdfa291185d7f --- /dev/null +++ b/sharding-proxy/src/test/resources/conf/server.yaml @@ -0,0 +1,14 @@ +orchestration: + name: orchestration_ds + overwrite: true + zookeeper: + namespace: orchestration + serverLists: localhost:2181 + +authentication: + username: root + password: root + +props: + max.connections.size.per.query: 1 + sql.show: false diff --git a/sharding-transaction/src/main/java/io/shardingsphere/transaction/manager/xa/atomikos/AtomikosTransactionManager.java b/sharding-transaction/src/main/java/io/shardingsphere/transaction/manager/xa/atomikos/AtomikosTransactionManager.java index d19d9cd9e04a4..b5a4d4244b3b7 100644 --- a/sharding-transaction/src/main/java/io/shardingsphere/transaction/manager/xa/atomikos/AtomikosTransactionManager.java +++ b/sharding-transaction/src/main/java/io/shardingsphere/transaction/manager/xa/atomikos/AtomikosTransactionManager.java @@ -17,6 +17,7 @@ package io.shardingsphere.transaction.manager.xa.atomikos; +import com.atomikos.beans.PropertyException; import com.atomikos.beans.PropertyUtils; import com.atomikos.icatch.jta.UserTransactionManager; import com.atomikos.jdbc.AtomikosDataSourceBean; @@ -90,7 +91,7 @@ public int getStatus() throws SQLException { } @Override - public DataSource wrapDataSource(final XADataSource xaDataSource, final String dataSourceName, final DataSourceParameter dataSourceParameter) throws Exception { + public DataSource wrapDataSource(final XADataSource xaDataSource, final String dataSourceName, final DataSourceParameter dataSourceParameter) throws PropertyException { AtomikosDataSourceBean result = new AtomikosDataSourceBean(); result.setUniqueResourceName(dataSourceName); result.setMaxPoolSize(dataSourceParameter.getMaximumPoolSize());