提交 cf1d3a4d 编写于 作者: H haocao

Add orchestration spring support 6th.

上级 59c1c11c
......@@ -22,11 +22,6 @@
<artifactId>sharding-jdbc-orchestration</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.shardingjdbc</groupId>
<artifactId>sharding-jdbc-spring</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
......
......@@ -7,6 +7,11 @@
</parent>
<artifactId>sharding-jdbc-orchestration-spring-boot-starter</artifactId>
<dependencies>
<dependency>
<groupId>io.shardingjdbc</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
......
......@@ -7,6 +7,11 @@
</parent>
<artifactId>sharding-jdbc-orchestration-spring-namespace</artifactId>
<dependencies>
<dependency>
<groupId>io.shardingjdbc</groupId>
<artifactId>sharding-jdbc-spring-namespace</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
......
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public abstract class AbstractShardingBothDataBasesAndTablesSpringDBUnitTest extends AbstractSpringDBUnitTest {
@Test
public void testWithAllPlaceholders() throws SQLException {
insertData();
selectData();
}
private void insertData() throws SQLException {
String orderSql = "INSERT INTO `t_order` (`order_id`, `user_id`, `status`) VALUES (?, ?, ?)";
String orderItemSql = "INSERT INTO `t_order_item` (`order_item_id`, `order_id`, `user_id`, `status`) VALUES (?, ?, ?, ?)";
String configSql = "INSERT INTO `t_config` (`id`, `status`) VALUES (?, ?)";
for (int orderId = 1; orderId <= 4; orderId++) {
for (int userId = 1; userId <= 2; userId++) {
try (Connection connection = getShardingDataSource().getConnection()) {
PreparedStatement preparedStatement = connection.prepareStatement(orderSql);
preparedStatement.setInt(1, orderId);
preparedStatement.setInt(2, userId);
preparedStatement.setString(3, "insert");
preparedStatement.execute();
preparedStatement.close();
preparedStatement = connection.prepareStatement(orderItemSql);
preparedStatement.setInt(1, orderId);
preparedStatement.setInt(2, orderId);
preparedStatement.setInt(3, userId);
preparedStatement.setString(4, "insert");
preparedStatement.execute();
preparedStatement.close();
preparedStatement = connection.prepareStatement(orderItemSql);
preparedStatement.setInt(1, orderId + 4);
preparedStatement.setInt(2, orderId);
preparedStatement.setInt(3, userId);
preparedStatement.setString(4, "insert");
preparedStatement.execute();
preparedStatement.close();
preparedStatement = connection.prepareStatement(configSql);
preparedStatement.setInt(1, new Long(System.nanoTime()).intValue());
preparedStatement.setString(2, "insert");
preparedStatement.execute();
preparedStatement.close();
}
}
}
}
private void selectData() throws SQLException {
String sql = "SELECT i.order_id, i.order_item_id FROM `t_order` o JOIN `t_order_item` i ON o.user_id = i.user_id AND o.order_id = i.order_id"
+ " WHERE o.`user_id` = ? AND o.`order_id` = ? AND i.`order_id` = ? ORDER BY i.order_item_id DESC";
try (Connection connection = getShardingDataSource().getConnection()) {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 1);
preparedStatement.setInt(2, 1);
preparedStatement.setInt(3, 1);
ResultSet resultSet = preparedStatement.executeQuery();
int count = 0;
while (resultSet.next()) {
if (0 == count) {
assertThat(resultSet.getInt(1), is(1));
assertThat(resultSet.getInt(2), is(5));
} else if (1 == count) {
assertThat(resultSet.getInt(1), is(1));
assertThat(resultSet.getInt(2), is(1));
}
count++;
}
preparedStatement.close();
}
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring;
import io.shardingjdbc.core.jdbc.core.datasource.ShardingDataSource;
import lombok.Getter;
import org.apache.commons.dbcp.BasicDataSource;
import org.h2.tools.RunScript;
import org.junit.Before;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.File;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
@TestExecutionListeners(inheritListeners = false, listeners =
{DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class})
public abstract class AbstractSpringDBUnitTest extends AbstractJUnit4SpringContextTests {
@Resource
@Getter
private ShardingDataSource shardingDataSource;
private final ClassLoader classLoader = AbstractSpringDBUnitTest.class.getClassLoader();
@Before
public void createSchema() throws SQLException {
for (String each : getSchemaFiles()) {
RunScript.execute(createDataSource(each).getConnection(), new InputStreamReader(classLoader.getResourceAsStream(each)));
}
}
private DataSource createDataSource(final String dataSetFile) {
BasicDataSource result = new BasicDataSource();
result.setDriverClassName(org.h2.Driver.class.getName());
result.setUrl(String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL", getFileName(dataSetFile)));
result.setUsername("sa");
result.setPassword("");
result.setMaxActive(100);
return result;
}
private String getFileName(final String dataSetFile) {
String fileName = new File(dataSetFile).getName();
if (-1 == fileName.lastIndexOf('.')) {
return fileName;
}
return fileName.substring(0, fileName.lastIndexOf('.'));
}
protected List<String> getSchemaFiles() {
return Arrays.asList("schema/dbtbl_0.sql", "schema/dbtbl_1.sql");
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring;
import io.shardingjdbc.orchestration.spring.cases.WithNamespaceAlgorithmClassTest;
import io.shardingjdbc.orchestration.spring.cases.WithNamespaceForMasterSlaveWithStrategyTypeTest;
import io.shardingjdbc.orchestration.spring.cases.WithNamespaceAlgorithmExpressionTest;
import io.shardingjdbc.orchestration.spring.cases.WithNamespaceBindingTablesTest;
import io.shardingjdbc.orchestration.spring.cases.WithNamespaceDefaultStrategyTest;
import io.shardingjdbc.orchestration.spring.cases.WithNamespaceDifferentTablesTest;
import io.shardingjdbc.orchestration.spring.cases.WithNamespaceForMasterSlaveWithDefaultStrategyTest;
import io.shardingjdbc.orchestration.spring.cases.WithNamespaceForMasterSlaveWithStrategyRefTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({
WithNamespaceAlgorithmClassTest.class,
WithNamespaceDifferentTablesTest.class,
WithNamespaceAlgorithmExpressionTest.class,
WithNamespaceDefaultStrategyTest.class,
WithNamespaceBindingTablesTest.class,
WithNamespaceDifferentTablesTest.class,
WithNamespaceForMasterSlaveWithDefaultStrategyTest.class,
WithNamespaceForMasterSlaveWithStrategyRefTest.class,
WithNamespaceForMasterSlaveWithStrategyTypeTest.class,
GenerateKeyDBUnitTest.class,
MasterSlaveNamespaceTest.class,
ShardingNamespaceTest.class
})
public class AllSpringTests {
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring;
import io.shardingjdbc.core.jdbc.core.datasource.ShardingDataSource;
import io.shardingjdbc.core.rule.TableRule;
import io.shardingjdbc.orchestration.spring.fixture.DecrementKeyGenerator;
import io.shardingjdbc.orchestration.spring.fixture.IncrementKeyGenerator;
import io.shardingjdbc.orchestration.spring.util.FieldValueUtil;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.Iterator;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@ContextConfiguration(locations = "classpath:META-INF/rdb/withNamespaceGenerateKeyColumns.xml")
public class GenerateKeyDBUnitTest extends AbstractSpringDBUnitTest {
@Resource
private ShardingDataSource shardingDataSource;
@Test
public void assertGenerateKey() throws SQLException {
try (Connection connection = getShardingDataSource().getConnection();
Statement statement = connection.createStatement()) {
statement.execute("INSERT INTO `t_order` (`user_id`, `status`) VALUES (1, 'init')", Statement.RETURN_GENERATED_KEYS);
ResultSet generateKeyResultSet = statement.getGeneratedKeys();
assertTrue(generateKeyResultSet.next());
assertThat(generateKeyResultSet.getLong(1), is(101L));
statement.execute("INSERT INTO `t_order_item` (`order_id`, `user_id`, `status`) VALUES (101, 1, 'init')", Statement.RETURN_GENERATED_KEYS);
generateKeyResultSet = statement.getGeneratedKeys();
assertTrue(generateKeyResultSet.next());
assertThat(generateKeyResultSet.getLong(1), is(99L));
}
}
@SuppressWarnings("unchecked")
@Test
public void assertGenerateKeyColumn() {
Object shardingContext = FieldValueUtil.getFieldValue(shardingDataSource, "shardingContext", true);
assertNotNull(shardingContext);
Object shardingRule = FieldValueUtil.getFieldValue(shardingContext, "shardingRule");
assertNotNull(shardingRule);
Object defaultKeyGenerator = FieldValueUtil.getFieldValue(shardingRule, "defaultKeyGenerator");
assertNotNull(defaultKeyGenerator);
assertTrue(defaultKeyGenerator instanceof IncrementKeyGenerator);
Object tableRules = FieldValueUtil.getFieldValue(shardingRule, "tableRules");
assertNotNull(tableRules);
assertThat(((Collection<TableRule>) tableRules).size(), is(2));
Iterator<TableRule> tableRuleIterator = ((Collection<TableRule>) tableRules).iterator();
TableRule orderRule = tableRuleIterator.next();
assertThat(orderRule.getGenerateKeyColumn(), is("order_id"));
TableRule orderItemRule = tableRuleIterator.next();
assertThat(orderItemRule.getGenerateKeyColumn(), is("order_item_id"));
assertTrue(orderItemRule.getKeyGenerator() instanceof DecrementKeyGenerator);
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring;
import io.shardingjdbc.orchestration.spring.util.FieldValueUtil;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import io.shardingjdbc.core.api.algorithm.masterslave.MasterSlaveLoadBalanceAlgorithm;
import io.shardingjdbc.core.api.algorithm.masterslave.RandomMasterSlaveLoadBalanceAlgorithm;
import io.shardingjdbc.core.api.algorithm.masterslave.RoundRobinMasterSlaveLoadBalanceAlgorithm;
import io.shardingjdbc.core.jdbc.core.datasource.MasterSlaveDataSource;
import io.shardingjdbc.core.jdbc.core.datasource.ShardingDataSource;
import io.shardingjdbc.core.rule.MasterSlaveRule;
import io.shardingjdbc.core.rule.ShardingRule;
import io.shardingjdbc.orchestration.spring.datasource.OrchestrationSpringMasterSlaveDataSource;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@ContextConfiguration(locations = "classpath:META-INF/rdb/masterSlaveNamespace.xml")
public class MasterSlaveNamespaceTest extends AbstractJUnit4SpringContextTests {
@Test
public void testDefaultMaserSlaveDataSource() {
MasterSlaveRule masterSlaveRule = getMasterSlaveRule("defaultMasterSlaveDataSource");
assertThat(masterSlaveRule.getMasterDataSourceName(), is("dbtbl_0_master"));
assertNotNull(masterSlaveRule.getSlaveDataSourceMap().get("dbtbl_0_slave_0"));
assertNotNull(masterSlaveRule.getSlaveDataSourceMap().get("dbtbl_0_slave_1"));
}
@Test
public void testTypeMasterSlaveDataSource() {
MasterSlaveRule randomSlaveRule = getMasterSlaveRule("randomMasterSlaveDataSource");
MasterSlaveRule roundRobinSlaveRule = getMasterSlaveRule("roundRobinMasterSlaveDataSource");
assertTrue(randomSlaveRule.getStrategy() instanceof RandomMasterSlaveLoadBalanceAlgorithm);
assertTrue(roundRobinSlaveRule.getStrategy() instanceof RoundRobinMasterSlaveLoadBalanceAlgorithm);
}
@Test
public void testRefMasterSlaveDataSource() {
MasterSlaveLoadBalanceAlgorithm randomStrategy = this.applicationContext.getBean("randomStrategy", MasterSlaveLoadBalanceAlgorithm.class);
MasterSlaveRule masterSlaveRule = getMasterSlaveRule("refMasterSlaveDataSource");
assertTrue(masterSlaveRule.getStrategy() == randomStrategy);
}
@Test
public void testDefaultShardingDataSource() {
ShardingRule shardingRule = getShardingRule("defaultShardingDataSource");
assertNotNull(shardingRule.getDataSourceMap().get("randomMasterSlaveDataSource"));
assertNotNull(shardingRule.getDataSourceMap().get("refMasterSlaveDataSource"));
assertThat(shardingRule.getDefaultDataSourceName(), is("randomMasterSlaveDataSource"));
assertThat(shardingRule.getTableRules().size(), is(1));
assertThat(shardingRule.getTableRules().iterator().next().getLogicTable(), is("t_order"));
}
@Test
public void testShardingDataSourceType() {
assertTrue(this.applicationContext.getBean("defaultMasterSlaveDataSource", MasterSlaveDataSource.class) instanceof OrchestrationSpringMasterSlaveDataSource);
}
private ShardingRule getShardingRule(final String shardingDataSourceName) {
ShardingDataSource shardingDataSource = this.applicationContext.getBean(shardingDataSourceName, ShardingDataSource.class);
Object shardingContext = FieldValueUtil.getFieldValue(shardingDataSource, "shardingContext", true);
return (ShardingRule) FieldValueUtil.getFieldValue(shardingContext, "shardingRule");
}
private MasterSlaveRule getMasterSlaveRule(final String masterSlaveDataSourceName) {
MasterSlaveDataSource masterSlaveDataSource = this.applicationContext.getBean(masterSlaveDataSourceName, MasterSlaveDataSource.class);
return (MasterSlaveRule) FieldValueUtil.getFieldValue(masterSlaveDataSource, "masterSlaveRule", true);
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring;
import io.shardingjdbc.core.api.config.strategy.ComplexShardingStrategyConfiguration;
import io.shardingjdbc.core.api.config.strategy.HintShardingStrategyConfiguration;
import io.shardingjdbc.core.api.config.strategy.InlineShardingStrategyConfiguration;
import io.shardingjdbc.core.api.config.strategy.NoneShardingStrategyConfiguration;
import io.shardingjdbc.core.api.config.strategy.StandardShardingStrategyConfiguration;
import io.shardingjdbc.core.constant.ShardingProperties;
import io.shardingjdbc.core.constant.ShardingPropertiesConstant;
import io.shardingjdbc.core.jdbc.core.datasource.ShardingDataSource;
import io.shardingjdbc.core.rule.BindingTableRule;
import io.shardingjdbc.core.rule.DataNode;
import io.shardingjdbc.core.rule.ShardingRule;
import io.shardingjdbc.core.rule.TableRule;
import io.shardingjdbc.orchestration.spring.datasource.OrchestrationSpringShardingDataSource;
import io.shardingjdbc.orchestration.spring.util.FieldValueUtil;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import java.util.Arrays;
import java.util.Iterator;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@ContextConfiguration(locations = "classpath:META-INF/rdb/shardingNamespace.xml")
public class ShardingNamespaceTest extends AbstractJUnit4SpringContextTests {
@Test
public void testStandardStrategy() {
StandardShardingStrategyConfiguration standardStrategy = this.applicationContext.getBean("standardStrategy", StandardShardingStrategyConfiguration.class);
assertThat(standardStrategy.getShardingColumn(), is("user_id"));
assertThat(standardStrategy.getPreciseAlgorithmClassName(), is("io.shardingjdbc.orchestration.spring.algorithm.PreciseModuloDatabaseShardingAlgorithm"));
}
@Test
public void testRangeStandardStrategy() {
StandardShardingStrategyConfiguration rangeStandardStrategy = this.applicationContext.getBean("rangeStandardStrategy", StandardShardingStrategyConfiguration.class);
assertThat(rangeStandardStrategy.getShardingColumn(), is("order_id"));
assertThat(rangeStandardStrategy.getPreciseAlgorithmClassName(), is("io.shardingjdbc.orchestration.spring.algorithm.PreciseModuloTableShardingAlgorithm"));
assertThat(rangeStandardStrategy.getRangeAlgorithmClassName(), is("io.shardingjdbc.orchestration.spring.algorithm.RangeModuloTableShardingAlgorithm"));
}
@Test
public void testComplexStrategy() {
ComplexShardingStrategyConfiguration complexStrategy = this.applicationContext.getBean("complexStrategy", ComplexShardingStrategyConfiguration.class);
assertThat(complexStrategy.getShardingColumns(), is("order_id,user_id"));
assertThat(complexStrategy.getAlgorithmClassName(), is("io.shardingjdbc.orchestration.spring.algorithm.DefaultComplexKeysShardingAlgorithm"));
}
@Test
public void testInlineStrategy() {
InlineShardingStrategyConfiguration inlineStrategy = this.applicationContext.getBean("inlineStrategy", InlineShardingStrategyConfiguration.class);
assertThat(inlineStrategy.getShardingColumn(), is("order_id"));
assertThat(inlineStrategy.getAlgorithmExpression(), is("t_order_${order_id % 4}"));
}
@Test
public void testHintStrategy() {
HintShardingStrategyConfiguration hintStrategy = this.applicationContext.getBean("hintStrategy", HintShardingStrategyConfiguration.class);
assertThat(hintStrategy.getAlgorithmClassName(), is("io.shardingjdbc.orchestration.spring.algorithm.DefaultHintShardingAlgorithm"));
}
@Test
public void testNoneStrategy() {
this.applicationContext.getBean("noneStrategy", NoneShardingStrategyConfiguration.class);
}
@Test
public void testSimpleShardingDataSource() {
ShardingRule shardingRule = getShardingRule("simpleShardingDataSource");
assertNotNull(shardingRule.getDataSourceMap().get("dbtbl_0"));
assertThat(shardingRule.getTableRules().size(), is(1));
assertThat(shardingRule.getTableRules().iterator().next().getLogicTable(), is("t_order"));
}
@Test
public void testShardingRuleWithAttributesDataSource() {
ShardingRule shardingRule = getShardingRule("shardingRuleWithAttributesDataSource");
assertNotNull(shardingRule.getDataSourceMap().get("dbtbl_0"));
assertNotNull(shardingRule.getDataSourceMap().get("dbtbl_1"));
assertThat(shardingRule.getDefaultDataSourceName(), is("dbtbl_0"));
assertTrue(Arrays.equals(shardingRule.getDefaultDatabaseShardingStrategy().getShardingColumns().toArray(new String[]{}),
new String[]{this.applicationContext.getBean("standardStrategy", StandardShardingStrategyConfiguration.class).getShardingColumn()}));
assertTrue(Arrays.equals(shardingRule.getDefaultTableShardingStrategy().getShardingColumns().toArray(new String[]{}),
new String[]{this.applicationContext.getBean("inlineStrategy", InlineShardingStrategyConfiguration.class).getShardingColumn()}));
assertThat(shardingRule.getDefaultKeyGenerator().getClass().getName(), is("io.shardingjdbc.orchestration.spring.fixture.IncrementKeyGenerator"));
}
@Test
public void testTableRuleWithAttributesDataSource() {
ShardingRule shardingRule = getShardingRule("tableRuleWithAttributesDataSource");
assertThat(shardingRule.getTableRules().size(), is(1));
TableRule tableRule = shardingRule.getTableRules().iterator().next();
assertThat(tableRule.getLogicTable(), is("t_order"));
assertThat(tableRule.getActualDataNodes().size(), is(8));
assertTrue(tableRule.getActualDataNodes().contains(new DataNode("dbtbl_0", "t_order_0")));
assertTrue(tableRule.getActualDataNodes().contains(new DataNode("dbtbl_0", "t_order_1")));
assertTrue(tableRule.getActualDataNodes().contains(new DataNode("dbtbl_0", "t_order_2")));
assertTrue(tableRule.getActualDataNodes().contains(new DataNode("dbtbl_0", "t_order_3")));
assertTrue(tableRule.getActualDataNodes().contains(new DataNode("dbtbl_1", "t_order_0")));
assertTrue(tableRule.getActualDataNodes().contains(new DataNode("dbtbl_1", "t_order_1")));
assertTrue(tableRule.getActualDataNodes().contains(new DataNode("dbtbl_1", "t_order_2")));
assertTrue(tableRule.getActualDataNodes().contains(new DataNode("dbtbl_1", "t_order_3")));
assertTrue(Arrays.equals(tableRule.getDatabaseShardingStrategy().getShardingColumns().toArray(new String[]{}),
new String[]{this.applicationContext.getBean("standardStrategy", StandardShardingStrategyConfiguration.class).getShardingColumn()}));
assertTrue(Arrays.equals(tableRule.getTableShardingStrategy().getShardingColumns().toArray(new String[]{}),
new String[]{this.applicationContext.getBean("inlineStrategy", InlineShardingStrategyConfiguration.class).getShardingColumn()}));
assertThat(tableRule.getGenerateKeyColumn(), is("order_id"));
assertThat(tableRule.getKeyGenerator().getClass().getName(), is("io.shardingjdbc.orchestration.spring.fixture.IncrementKeyGenerator"));
}
@Test
public void testMultiTableRulesDataSource() {
ShardingRule shardingRule = getShardingRule("multiTableRulesDataSource");
assertThat(shardingRule.getTableRules().size(), is(2));
Iterator<TableRule> iter = shardingRule.getTableRules().iterator();
assertThat(iter.next().getLogicTable(), is("t_order"));
assertThat(iter.next().getLogicTable(), is("t_order_item"));
}
@Test
public void testBindingTableRuleDatasource() {
ShardingRule shardingRule = getShardingRule("bindingTableRuleDatasource");
assertThat(shardingRule.getBindingTableRules().size(), is(1));
BindingTableRule bindingTableRule = shardingRule.getBindingTableRules().iterator().next();
assertThat(bindingTableRule.getBindingActualTable("dbtbl_0", "t_order", "t_order_item"), is("t_order"));
assertThat(bindingTableRule.getBindingActualTable("dbtbl_1", "t_order", "t_order_item"), is("t_order"));
}
@Test
public void testMultiBindingTableRulesDatasource() {
ShardingRule shardingRule = getShardingRule("multiBindingTableRulesDatasource");
assertThat(shardingRule.getBindingTableRules().size(), is(2));
Iterator<BindingTableRule> iter = shardingRule.getBindingTableRules().iterator();
BindingTableRule orderRule = iter.next();
assertThat(orderRule.getBindingActualTable("dbtbl_0", "t_order", "t_order_item"), is("t_order"));
assertThat(orderRule.getBindingActualTable("dbtbl_1", "t_order", "t_order_item"), is("t_order"));
BindingTableRule userRule = iter.next();
assertThat(userRule.getBindingActualTable("dbtbl_0", "t_user", "t_user_detail"), is("t_user"));
assertThat(userRule.getBindingActualTable("dbtbl_1", "t_user", "t_user_detail"), is("t_user"));
}
@Test
public void testPropsDataSource() {
ShardingDataSource shardingDataSource = this.applicationContext.getBean("propsDataSource", ShardingDataSource.class);
Object shardingContext = FieldValueUtil.getFieldValue(shardingDataSource, "shardingContext", true);
assertTrue((boolean) FieldValueUtil.getFieldValue(shardingContext, "showSQL"));
ShardingProperties shardingProperties = (ShardingProperties) FieldValueUtil.getFieldValue(shardingDataSource, "shardingProperties", true);
boolean showSql = shardingProperties.getValue(ShardingPropertiesConstant.SQL_SHOW);
assertTrue(showSql);
int executorSize = shardingProperties.getValue(ShardingPropertiesConstant.EXECUTOR_SIZE);
assertThat(executorSize, is(10));
assertNull(ShardingPropertiesConstant.findByKey("foo"));
}
@Test
public void testShardingDataSourceType() {
assertTrue(this.applicationContext.getBean("simpleShardingDataSource", ShardingDataSource.class) instanceof OrchestrationSpringShardingDataSource);
}
@Test
public void testDefaultActualDataNodes() {
ShardingDataSource multiTableRulesDataSource = this.applicationContext.getBean("multiTableRulesDataSource", ShardingDataSource.class);
Object shardingContext = FieldValueUtil.getFieldValue(multiTableRulesDataSource, "shardingContext", true);
ShardingRule shardingRule = (ShardingRule) FieldValueUtil.getFieldValue(shardingContext, "shardingRule");
assertThat(shardingRule.getTableRules().size(), is(2));
Iterator<TableRule> iter = shardingRule.getTableRules().iterator();
TableRule orderRule = iter.next();
assertThat(orderRule.getActualDataNodes().size(), is(2));
assertTrue(orderRule.getActualDataNodes().contains(new DataNode("dbtbl_0", "t_order")));
assertTrue(orderRule.getActualDataNodes().contains(new DataNode("dbtbl_1", "t_order")));
TableRule orderItemRule = iter.next();
assertThat(orderItemRule.getActualDataNodes().size(), is(2));
assertTrue(orderItemRule.getActualDataNodes().contains(new DataNode("dbtbl_0", "t_order_item")));
assertTrue(orderItemRule.getActualDataNodes().contains(new DataNode("dbtbl_1", "t_order_item")));
}
private ShardingRule getShardingRule(final String shardingDataSourceName) {
ShardingDataSource shardingDataSource = this.applicationContext.getBean(shardingDataSourceName, ShardingDataSource.class);
Object shardingContext = FieldValueUtil.getFieldValue(shardingDataSource, "shardingContext", true);
return (ShardingRule) FieldValueUtil.getFieldValue(shardingContext, "shardingRule");
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.algorithm;
import java.util.Collection;
import io.shardingjdbc.core.api.algorithm.sharding.ShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.complex.ComplexKeysShardingAlgorithm;
public class DefaultComplexKeysShardingAlgorithm implements ComplexKeysShardingAlgorithm {
@Override
public Collection<String> doSharding(final Collection<String> availableTargetNames, final Collection<ShardingValue> shardingValues) {
return availableTargetNames;
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.algorithm;
import java.util.Collection;
import io.shardingjdbc.core.api.algorithm.sharding.ShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.hint.HintShardingAlgorithm;
public class DefaultHintShardingAlgorithm implements HintShardingAlgorithm {
@Override
public Collection<String> doSharding(final Collection<String> availableTargetNames, final ShardingValue shardingValue) {
return availableTargetNames;
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.algorithm;
import io.shardingjdbc.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import java.util.Collection;
public class PreciseModuloDatabaseShardingAlgorithm implements PreciseShardingAlgorithm<Integer> {
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Integer> shardingValue) {
for (String each : availableTargetNames) {
if (each.endsWith(shardingValue.getValue() % 2 + "")) {
return each;
}
}
throw new UnsupportedOperationException();
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.algorithm;
import io.shardingjdbc.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import java.util.Collection;
public class PreciseModuloTableShardingAlgorithm implements PreciseShardingAlgorithm<Integer> {
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Integer> shardingValue) {
for (String each : availableTargetNames) {
if (each.endsWith(shardingValue.getValue() % 4 + "")) {
return each;
}
}
throw new UnsupportedOperationException();
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.algorithm;
import io.shardingjdbc.core.api.algorithm.sharding.RangeShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.standard.RangeShardingAlgorithm;
import com.google.common.collect.Range;
import java.util.Collection;
import java.util.LinkedHashSet;
public class RangeModuloDatabaseShardingAlgorithm implements RangeShardingAlgorithm<Integer> {
@Override
public Collection<String> doSharding(final Collection<String> availableTargetNames, final RangeShardingValue<Integer> shardingValue) {
Collection<String> result = new LinkedHashSet<>(availableTargetNames.size());
Range<Integer> range = shardingValue.getValueRange();
for (Integer i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) {
for (String each : availableTargetNames) {
if (each.endsWith(i % 2 + "")) {
result.add(each);
}
}
}
return result;
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.algorithm;
import io.shardingjdbc.core.api.algorithm.sharding.RangeShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.standard.RangeShardingAlgorithm;
import com.google.common.collect.Range;
import java.util.Collection;
import java.util.LinkedHashSet;
public class RangeModuloTableShardingAlgorithm implements RangeShardingAlgorithm<Integer> {
@Override
public Collection<String> doSharding(final Collection<String> availableTargetNames, final RangeShardingValue<Integer> shardingValue) {
Collection<String> result = new LinkedHashSet<>(availableTargetNames.size());
Range<Integer> range = shardingValue.getValueRange();
for (Integer i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) {
for (String each : availableTargetNames) {
if (each.endsWith(i % 4 + "")) {
result.add(each);
}
}
}
return result;
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.cases;
import io.shardingjdbc.orchestration.spring.AbstractShardingBothDataBasesAndTablesSpringDBUnitTest;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(locations = "classpath:META-INF/rdb/withNamespaceAlgorithmClass.xml")
public final class WithNamespaceAlgorithmClassTest extends AbstractShardingBothDataBasesAndTablesSpringDBUnitTest {
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.cases;
import io.shardingjdbc.orchestration.spring.AbstractShardingBothDataBasesAndTablesSpringDBUnitTest;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(locations = "classpath:META-INF/rdb/withNamespaceAlgorithmExpression.xml")
public final class WithNamespaceAlgorithmExpressionTest extends AbstractShardingBothDataBasesAndTablesSpringDBUnitTest {
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.cases;
import io.shardingjdbc.orchestration.spring.AbstractShardingBothDataBasesAndTablesSpringDBUnitTest;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(locations = "classpath:META-INF/rdb/withNamespaceBindingTables.xml")
public final class WithNamespaceBindingTablesTest extends AbstractShardingBothDataBasesAndTablesSpringDBUnitTest {
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.cases;
import io.shardingjdbc.orchestration.spring.AbstractShardingBothDataBasesAndTablesSpringDBUnitTest;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(locations = "classpath:META-INF/rdb/withNamespaceDefaultStrategy.xml")
public final class WithNamespaceDefaultStrategyTest extends AbstractShardingBothDataBasesAndTablesSpringDBUnitTest {
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.cases;
import io.shardingjdbc.orchestration.spring.AbstractShardingBothDataBasesAndTablesSpringDBUnitTest;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(locations = "classpath:META-INF/rdb/withNamespaceDifferentTables.xml")
public final class WithNamespaceDifferentTablesTest extends AbstractShardingBothDataBasesAndTablesSpringDBUnitTest {
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.cases;
import io.shardingjdbc.orchestration.spring.AbstractShardingBothDataBasesAndTablesSpringDBUnitTest;
import java.util.Arrays;
import java.util.List;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(locations = "classpath:META-INF/rdb/withNamespaceForMasterSlaveWithDefaultStrategy.xml")
public final class WithNamespaceForMasterSlaveWithDefaultStrategyTest extends AbstractShardingBothDataBasesAndTablesSpringDBUnitTest {
@Override
protected List<String> getSchemaFiles() {
return Arrays.asList("schema/dbtbl_0_master.sql", "schema/dbtbl_0_slave_0.sql", "schema/dbtbl_0_slave_1.sql",
"schema/dbtbl_1_master.sql", "schema/dbtbl_1_slave_0.sql", "schema/dbtbl_1_slave_1.sql");
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.cases;
import io.shardingjdbc.orchestration.spring.AbstractShardingBothDataBasesAndTablesSpringDBUnitTest;
import org.springframework.test.context.ContextConfiguration;
import java.util.Arrays;
import java.util.List;
@ContextConfiguration(locations = "classpath:META-INF/rdb/withNamespaceForMasterSlaveWithStrategyRef.xml")
public final class WithNamespaceForMasterSlaveWithStrategyRefTest extends AbstractShardingBothDataBasesAndTablesSpringDBUnitTest {
@Override
protected List<String> getSchemaFiles() {
return Arrays.asList("schema/dbtbl_0_master.sql", "schema/dbtbl_0_slave_0.sql", "schema/dbtbl_0_slave_1.sql",
"schema/dbtbl_1_master.sql", "schema/dbtbl_1_slave_0.sql", "schema/dbtbl_1_slave_1.sql");
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.cases;
import io.shardingjdbc.orchestration.spring.AbstractShardingBothDataBasesAndTablesSpringDBUnitTest;
import org.springframework.test.context.ContextConfiguration;
import java.util.Arrays;
import java.util.List;
@ContextConfiguration(locations = "classpath:META-INF/rdb/withNamespaceForMasterSlaveWithStrategyType.xml")
public final class WithNamespaceForMasterSlaveWithStrategyTypeTest extends AbstractShardingBothDataBasesAndTablesSpringDBUnitTest {
@Override
protected List<String> getSchemaFiles() {
return Arrays.asList("schema/dbtbl_0_master.sql", "schema/dbtbl_0_slave_0.sql", "schema/dbtbl_0_slave_1.sql",
"schema/dbtbl_1_master.sql", "schema/dbtbl_1_slave_0.sql", "schema/dbtbl_1_slave_1.sql");
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.fixture;
import io.shardingjdbc.core.keygen.KeyGenerator;
import java.util.concurrent.atomic.AtomicInteger;
public final class DecrementKeyGenerator implements KeyGenerator {
private final AtomicInteger sequence = new AtomicInteger(100);
@Override
public Number generateKey() {
return sequence.decrementAndGet();
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.fixture;
import io.shardingjdbc.core.keygen.KeyGenerator;
import java.util.concurrent.atomic.AtomicInteger;
public final class IncrementKeyGenerator implements KeyGenerator {
private final AtomicInteger sequence = new AtomicInteger(100);
@Override
public Number generateKey() {
return sequence.incrementAndGet();
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package io.shardingjdbc.orchestration.spring.util;
import com.google.common.base.Strings;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.lang.reflect.Field;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class FieldValueUtil {
private static Object getFieldValue(final Class<?> clazz, final Object obj, final String fieldName) {
try {
Field field = clazz.getDeclaredField(fieldName);
if (!field.isAccessible()) {
field.setAccessible(true);
}
return field.get(obj);
} catch (final NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
public static Object getFieldValue(final Object obj, final String fieldName, final boolean fromSuperclass) {
if (null == obj || Strings.isNullOrEmpty(fieldName)) {
return null;
}
Class<?> clazz = fromSuperclass ? obj.getClass().getSuperclass() : obj.getClass();
return getFieldValue(clazz, obj, fieldName);
}
public static Object getFieldValue(final Object obj, final String fieldName) {
return getFieldValue(obj, fieldName, false);
}
}
......@@ -28,7 +28,6 @@ import org.springframework.context.ApplicationContextAware;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Map;
import java.util.Map.Entry;
/**
* Master-slave datasource for spring namespace.
......@@ -54,13 +53,4 @@ public class SpringMasterSlaveDataSource extends MasterSlaveDataSource implement
final Map<String, DataSource> slaveDataSourceMap, final MasterSlaveLoadBalanceAlgorithmType strategyType) throws SQLException {
super(new MasterSlaveRule(name, masterDataSourceName, masterDataSource, slaveDataSourceMap, strategyType.getAlgorithm()));
}
@Override
public void renew(final MasterSlaveRule masterSlaveRule) throws SQLException {
DataSourceBeanUtil.createDataSourceBean(applicationContext, masterSlaveRule.getMasterDataSourceName(), masterSlaveRule.getMasterDataSource());
for (Entry<String, DataSource> entry : masterSlaveRule.getSlaveDataSourceMap().entrySet()) {
DataSourceBeanUtil.createDataSourceBean(applicationContext, entry.getKey(), entry.getValue());
}
super.renew(masterSlaveRule);
}
}
......@@ -18,9 +18,7 @@
package io.shardingjdbc.spring.datasource;
import io.shardingjdbc.core.api.config.ShardingRuleConfiguration;
import io.shardingjdbc.core.jdbc.core.datasource.MasterSlaveDataSource;
import io.shardingjdbc.core.jdbc.core.datasource.ShardingDataSource;
import io.shardingjdbc.core.rule.ShardingRule;
import lombok.Setter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
......@@ -28,14 +26,12 @@ import org.springframework.context.ApplicationContextAware;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
/**
* Sharding datasource for spring namespace.
*
* @author caohao
* @author zhanglaing
*/
public class SpringShardingDataSource extends ShardingDataSource implements ApplicationContextAware {
......@@ -45,18 +41,4 @@ public class SpringShardingDataSource extends ShardingDataSource implements Appl
public SpringShardingDataSource(final Map<String, DataSource> dataSourceMap, final ShardingRuleConfiguration shardingRuleConfig, final Properties props) throws SQLException {
super(shardingRuleConfig.build(dataSourceMap), props);
}
@Override
public void renew(final ShardingRule newShardingRule, final Properties newProps) throws SQLException {
for (Entry<String, DataSource> entry : newShardingRule.getDataSourceMap().entrySet()) {
if (entry.getValue() instanceof MasterSlaveDataSource) {
for (Entry<String, DataSource> masterSlaveEntry : ((MasterSlaveDataSource) entry.getValue()).getAllDataSources().entrySet()) {
DataSourceBeanUtil.createDataSourceBean(applicationContext, masterSlaveEntry.getKey(), masterSlaveEntry.getValue());
}
} else {
DataSourceBeanUtil.createDataSourceBean(applicationContext, entry.getKey(), entry.getValue());
}
}
super.renew(newShardingRule, newProps);
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册