未验证 提交 921c9404 编写于 作者: T TaoZhi 提交者: GitHub

make key-generator as a spring bean on spring namespace. (#4945)

* make key-generator as a spring bean on spring namespace.

* fix checkstyle.

* code refactor for make key-generator as a spring bean.

* add test for GenerateKeyAlgorithmFactoryBean.

* rename ShardingKeyGenerator SPI to KeyGenerateAlgorithm.

* rename method containsKeyGeneratorConfiguration to containsKeyGenerateAlgorithm.
Co-authored-by: Ntaozhi3 <taozhi1@jd.com>
上级 43d3426f
......@@ -20,27 +20,21 @@ package org.apache.shardingsphere.api.config.sharding;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import lombok.Getter;
import org.apache.shardingsphere.underlying.common.config.TypeBasedSPIConfiguration;
import java.util.Properties;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
/**
* Key generator configuration.
*/
@Getter
public final class KeyGeneratorConfiguration extends TypeBasedSPIConfiguration {
public final class KeyGeneratorConfiguration {
private final String column;
public KeyGeneratorConfiguration(final String type, final String column) {
super(type);
Preconditions.checkArgument(!Strings.isNullOrEmpty(column), "Column is required.");
this.column = column;
}
private final KeyGenerateAlgorithm keyGenerateAlgorithm;
public KeyGeneratorConfiguration(final String type, final String column, final Properties properties) {
super(type, properties);
public KeyGeneratorConfiguration(final String column, final KeyGenerateAlgorithm keyGenerateAlgorithm) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(column), "Column is required.");
this.column = column;
this.keyGenerateAlgorithm = keyGenerateAlgorithm;
}
}
......@@ -20,9 +20,9 @@ package org.apache.shardingsphere.spi.keygen;
import org.apache.shardingsphere.spi.TypeBasedSPI;
/**
* Key generator.
* Key generate algorithm.
*/
public interface ShardingKeyGenerator extends TypeBasedSPI {
public interface KeyGenerateAlgorithm extends TypeBasedSPI {
/**
* Generate key.
......
......@@ -19,38 +19,15 @@ package org.apache.shardingsphere.api.config.sharding;
import org.junit.Test;
import java.util.Properties;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public final class KeyGeneratorConfigurationTest {
@Test(expected = IllegalArgumentException.class)
public void assertConstructorWithoutType() {
new KeyGeneratorConfiguration("", "id", new Properties());
@Test
public void assertConstructorWithoutKeyGenerator() {
new KeyGeneratorConfiguration("id", null);
}
@Test(expected = IllegalArgumentException.class)
public void assertConstructorWithoutColumn() {
new KeyGeneratorConfiguration("TEST", "", new Properties());
}
@Test
public void assertConstructorWithoutProperties() {
KeyGeneratorConfiguration actual = new KeyGeneratorConfiguration("TEST", "id", null);
assertThat(actual.getType(), is("TEST"));
assertThat(actual.getColumn(), is("id"));
assertThat(actual.getProperties(), is(new Properties()));
}
@Test
public void assertConstructorWithFullArguments() {
Properties props = new Properties();
props.setProperty("key", "value");
KeyGeneratorConfiguration actual = new KeyGeneratorConfiguration("TEST", "id", props);
assertThat(actual.getType(), is("TEST"));
assertThat(actual.getColumn(), is("id"));
assertThat(actual.getProperties(), is(props));
new KeyGeneratorConfiguration("", null);
}
}
......@@ -30,8 +30,8 @@ import org.apache.shardingsphere.core.strategy.route.ShardingStrategyFactory;
import org.apache.shardingsphere.core.strategy.route.none.NoneShardingStrategy;
import org.apache.shardingsphere.encrypt.api.EncryptRuleConfiguration;
import org.apache.shardingsphere.encrypt.rule.EncryptRule;
import org.apache.shardingsphere.spi.algorithm.keygen.ShardingKeyGeneratorServiceLoader;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.apache.shardingsphere.spi.algorithm.keygen.KeyGenerateAlgorithmServiceLoader;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import org.apache.shardingsphere.underlying.common.config.exception.ShardingSphereConfigurationException;
import org.apache.shardingsphere.underlying.common.rule.BaseRule;
import org.apache.shardingsphere.underlying.common.rule.DataNode;
......@@ -65,7 +65,7 @@ public class ShardingRule implements BaseRule {
private final ShardingStrategy defaultTableShardingStrategy;
private final ShardingKeyGenerator defaultShardingKeyGenerator;
private final KeyGenerateAlgorithm defaultKeyGenerateAlgorithm;
private final Collection<MasterSlaveRule> masterSlaveRules;
......@@ -81,7 +81,7 @@ public class ShardingRule implements BaseRule {
bindingTableRules = createBindingTableRules(shardingRuleConfig.getBindingTableGroups());
defaultDatabaseShardingStrategy = createDefaultShardingStrategy(shardingRuleConfig.getDefaultDatabaseShardingStrategyConfig());
defaultTableShardingStrategy = createDefaultShardingStrategy(shardingRuleConfig.getDefaultTableShardingStrategyConfig());
defaultShardingKeyGenerator = createDefaultKeyGenerator(shardingRuleConfig.getDefaultKeyGeneratorConfig());
defaultKeyGenerateAlgorithm = createDefaultKeyGenerateAlgorithm(shardingRuleConfig.getDefaultKeyGeneratorConfig());
masterSlaveRules = createMasterSlaveRules(shardingRuleConfig.getMasterSlaveRuleConfigs());
encryptRule = createEncryptRule(shardingRuleConfig.getEncryptRuleConfig());
}
......@@ -108,14 +108,13 @@ public class ShardingRule implements BaseRule {
return Optional.ofNullable(shardingStrategyConfiguration).map(ShardingStrategyFactory::newInstance).orElse(new NoneShardingStrategy());
}
private ShardingKeyGenerator createDefaultKeyGenerator(final KeyGeneratorConfiguration keyGeneratorConfiguration) {
ShardingKeyGeneratorServiceLoader serviceLoader = new ShardingKeyGeneratorServiceLoader();
return containsKeyGeneratorConfiguration(keyGeneratorConfiguration)
? serviceLoader.newService(keyGeneratorConfiguration.getType(), keyGeneratorConfiguration.getProperties()) : serviceLoader.newService();
private KeyGenerateAlgorithm createDefaultKeyGenerateAlgorithm(final KeyGeneratorConfiguration keyGeneratorConfiguration) {
KeyGenerateAlgorithmServiceLoader serviceLoader = new KeyGenerateAlgorithmServiceLoader();
return containsKeyGenerateAlgorithm(keyGeneratorConfiguration) ? keyGeneratorConfiguration.getKeyGenerateAlgorithm() : serviceLoader.newService();
}
private boolean containsKeyGeneratorConfiguration(final KeyGeneratorConfiguration keyGeneratorConfiguration) {
return null != keyGeneratorConfiguration && !Strings.isNullOrEmpty(keyGeneratorConfiguration.getType());
private boolean containsKeyGenerateAlgorithm(final KeyGeneratorConfiguration keyGeneratorConfiguration) {
return null != keyGeneratorConfiguration && null != keyGeneratorConfiguration.getKeyGenerateAlgorithm();
}
private Collection<MasterSlaveRule> createMasterSlaveRules(final Collection<MasterSlaveRuleConfiguration> masterSlaveRuleConfigurations) {
......@@ -320,7 +319,7 @@ public class ShardingRule implements BaseRule {
if (!tableRule.isPresent()) {
throw new ShardingSphereConfigurationException("Cannot find strategy for generate keys.");
}
return Optional.ofNullable(tableRule.get().getShardingKeyGenerator()).orElse(defaultShardingKeyGenerator).generateKey();
return Optional.ofNullable(tableRule.get().getKeyGenerateAlgorithm()).orElse(defaultKeyGenerateAlgorithm).generateKey();
}
/**
......
......@@ -26,8 +26,7 @@ import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.core.strategy.route.ShardingStrategy;
import org.apache.shardingsphere.core.strategy.route.ShardingStrategyFactory;
import org.apache.shardingsphere.core.strategy.route.none.NoneShardingStrategy;
import org.apache.shardingsphere.spi.algorithm.keygen.ShardingKeyGeneratorServiceLoader;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import org.apache.shardingsphere.underlying.common.config.exception.ShardingSphereConfigurationException;
import org.apache.shardingsphere.underlying.common.config.inline.InlineExpressionParser;
import org.apache.shardingsphere.underlying.common.exception.ShardingSphereException;
......@@ -69,7 +68,7 @@ public final class TableRule {
@Getter(AccessLevel.NONE)
private final String generateKeyColumn;
private final ShardingKeyGenerator shardingKeyGenerator;
private final KeyGenerateAlgorithm keyGenerateAlgorithm;
private final Collection<String> actualDatasourceNames = new LinkedHashSet<>();
......@@ -84,7 +83,7 @@ public final class TableRule {
databaseShardingStrategy = null;
tableShardingStrategy = null;
generateKeyColumn = null;
shardingKeyGenerator = null;
keyGenerateAlgorithm = null;
}
public TableRule(final Collection<String> dataSourceNames, final String logicTableName) {
......@@ -95,7 +94,7 @@ public final class TableRule {
databaseShardingStrategy = null;
tableShardingStrategy = null;
generateKeyColumn = null;
shardingKeyGenerator = null;
keyGenerateAlgorithm = null;
}
public TableRule(final TableRuleConfiguration tableRuleConfig, final ShardingDataSourceNames shardingDataSourceNames, final String defaultGenerateKeyColumn) {
......@@ -109,8 +108,7 @@ public final class TableRule {
tableShardingStrategy = null == tableRuleConfig.getTableShardingStrategyConfig() ? null : ShardingStrategyFactory.newInstance(tableRuleConfig.getTableShardingStrategyConfig());
final KeyGeneratorConfiguration keyGeneratorConfiguration = tableRuleConfig.getKeyGeneratorConfig();
generateKeyColumn = null != keyGeneratorConfiguration && !Strings.isNullOrEmpty(keyGeneratorConfiguration.getColumn()) ? keyGeneratorConfiguration.getColumn() : defaultGenerateKeyColumn;
shardingKeyGenerator = containsKeyGeneratorConfiguration(tableRuleConfig)
? new ShardingKeyGeneratorServiceLoader().newService(tableRuleConfig.getKeyGeneratorConfig().getType(), tableRuleConfig.getKeyGeneratorConfig().getProperties()) : null;
keyGenerateAlgorithm = containsKeyGenerateAlgorithm(tableRuleConfig) ? tableRuleConfig.getKeyGeneratorConfig().getKeyGenerateAlgorithm() : null;
checkRule(dataNodes);
}
......@@ -129,8 +127,8 @@ public final class TableRule {
datasourceToTablesMap.computeIfAbsent(datasourceName, k -> new LinkedHashSet<>()).add(tableName);
}
private boolean containsKeyGeneratorConfiguration(final TableRuleConfiguration tableRuleConfiguration) {
return null != tableRuleConfiguration.getKeyGeneratorConfig() && !Strings.isNullOrEmpty(tableRuleConfiguration.getKeyGeneratorConfig().getType());
private boolean containsKeyGenerateAlgorithm(final TableRuleConfiguration tableRuleConfiguration) {
return null != tableRuleConfiguration.getKeyGeneratorConfig() && null != tableRuleConfiguration.getKeyGeneratorConfig().getKeyGenerateAlgorithm();
}
private boolean isEmptyDataNodes(final List<String> dataNodes) {
......@@ -220,7 +218,7 @@ public final class TableRule {
/**
* Get generate key column.
*
*
* @return generate key column
*/
public Optional<String> getGenerateKeyColumn() {
......
......@@ -21,13 +21,13 @@ import com.google.common.base.Preconditions;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import java.util.Calendar;
import java.util.Properties;
/**
* Snowflake distributed primary key generator.
* Snowflake distributed primary key generate algorithm.
*
* <p>
* Use snowflake algorithm. Length is 64 bit.
......@@ -41,14 +41,14 @@ import java.util.Properties;
* </pre>
*
* <p>
* Call @{@code SnowflakeShardingKeyGenerator.setWorkerId} to set worker id, default value is 0.
* Call @{@code SnowflakeKeyGenerateAlgorithm.setWorkerId} to set worker id, default value is 0.
* </p>
*
* <p>
* Call @{@code SnowflakeShardingKeyGenerator.setMaxTolerateTimeDifferenceMilliseconds} to set max tolerate time difference milliseconds, default value is 0.
* Call @{@code SnowflakeKeyGenerateAlgorithm.setMaxTolerateTimeDifferenceMilliseconds} to set max tolerate time difference milliseconds, default value is 0.
* </p>
*/
public final class SnowflakeShardingKeyGenerator implements ShardingKeyGenerator {
public final class SnowflakeKeyGenerateAlgorithm implements KeyGenerateAlgorithm {
public static final long EPOCH;
......
......@@ -19,17 +19,17 @@ package org.apache.shardingsphere.core.strategy.keygen;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import java.util.Properties;
import java.util.UUID;
/**
* UUID key generator.
* UUID key generate algorithm.
*/
@Getter
@Setter
public final class UUIDShardingKeyGenerator implements ShardingKeyGenerator {
public final class UUIDKeyGenerateAlgorithm implements KeyGenerateAlgorithm {
private Properties properties = new Properties();
......
......@@ -19,6 +19,8 @@ package org.apache.shardingsphere.core.yaml.swapper;
import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.core.yaml.config.sharding.YamlKeyGeneratorConfiguration;
import org.apache.shardingsphere.spi.algorithm.keygen.KeyGenerateAlgorithmServiceLoader;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import org.apache.shardingsphere.underlying.common.yaml.swapper.YamlSwapper;
/**
......@@ -29,14 +31,15 @@ public final class KeyGeneratorConfigurationYamlSwapper implements YamlSwapper<Y
@Override
public YamlKeyGeneratorConfiguration swap(final KeyGeneratorConfiguration data) {
YamlKeyGeneratorConfiguration result = new YamlKeyGeneratorConfiguration();
result.setType(data.getType());
result.setType(data.getKeyGenerateAlgorithm().getType());
result.setColumn(data.getColumn());
result.setProps(data.getProperties());
result.setProps(data.getKeyGenerateAlgorithm().getProperties());
return result;
}
@Override
public KeyGeneratorConfiguration swap(final YamlKeyGeneratorConfiguration yamlConfiguration) {
return new KeyGeneratorConfiguration(yamlConfiguration.getType(), yamlConfiguration.getColumn(), yamlConfiguration.getProps());
KeyGenerateAlgorithm keyGenerateAlgorithm = new KeyGenerateAlgorithmServiceLoader().newService(yamlConfiguration.getType(), yamlConfiguration.getProps());
return new KeyGeneratorConfiguration(yamlConfiguration.getColumn(), keyGenerateAlgorithm);
}
}
......@@ -19,18 +19,18 @@ package org.apache.shardingsphere.spi.algorithm.keygen;
import org.apache.shardingsphere.spi.NewInstanceServiceLoader;
import org.apache.shardingsphere.spi.TypeBasedSPIServiceLoader;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
/**
* Key generator service loader.
* Key generate algorithm service loader.
*/
public final class ShardingKeyGeneratorServiceLoader extends TypeBasedSPIServiceLoader<ShardingKeyGenerator> {
public final class KeyGenerateAlgorithmServiceLoader extends TypeBasedSPIServiceLoader<KeyGenerateAlgorithm> {
static {
NewInstanceServiceLoader.register(ShardingKeyGenerator.class);
NewInstanceServiceLoader.register(KeyGenerateAlgorithm.class);
}
public ShardingKeyGeneratorServiceLoader() {
super(ShardingKeyGenerator.class);
public KeyGenerateAlgorithmServiceLoader() {
super(KeyGenerateAlgorithm.class);
}
}
......@@ -15,5 +15,5 @@
# limitations under the License.
#
org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator
org.apache.shardingsphere.core.strategy.keygen.UUIDShardingKeyGenerator
org.apache.shardingsphere.core.strategy.keygen.SnowflakeKeyGenerateAlgorithm
org.apache.shardingsphere.core.strategy.keygen.UUIDKeyGenerateAlgorithm
......@@ -17,6 +17,18 @@
package org.apache.shardingsphere.core.rule;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Properties;
import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
......@@ -25,28 +37,17 @@ import org.apache.shardingsphere.api.config.sharding.strategy.InlineShardingStra
import org.apache.shardingsphere.api.config.sharding.strategy.NoneShardingStrategyConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.StandardShardingStrategyConfiguration;
import org.apache.shardingsphere.core.shard.fixture.PreciseShardingAlgorithmFixture;
import org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator;
import org.apache.shardingsphere.core.strategy.keygen.fixture.IncrementShardingKeyGenerator;
import org.apache.shardingsphere.core.strategy.keygen.SnowflakeKeyGenerateAlgorithm;
import org.apache.shardingsphere.core.strategy.keygen.fixture.IncrementKeyGenerateAlgorithm;
import org.apache.shardingsphere.core.strategy.route.ShardingStrategy;
import org.apache.shardingsphere.core.strategy.route.inline.InlineShardingStrategy;
import org.apache.shardingsphere.core.strategy.route.none.NoneShardingStrategy;
import org.apache.shardingsphere.spi.algorithm.keygen.KeyGenerateAlgorithmServiceLoader;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import org.apache.shardingsphere.underlying.common.config.exception.ShardingSphereConfigurationException;
import org.apache.shardingsphere.underlying.common.rule.DataNode;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Properties;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public final class ShardingRuleTest {
@Test(expected = IllegalArgumentException.class)
......@@ -63,7 +64,7 @@ public final class ShardingRuleTest {
assertThat(actual.getBroadcastTables(), is(Collections.singletonList("BROADCAST_TABLE")));
assertThat(actual.getDefaultDatabaseShardingStrategy(), instanceOf(InlineShardingStrategy.class));
assertThat(actual.getDefaultTableShardingStrategy(), instanceOf(InlineShardingStrategy.class));
assertThat(actual.getDefaultShardingKeyGenerator(), instanceOf(IncrementShardingKeyGenerator.class));
assertThat(actual.getDefaultKeyGenerateAlgorithm(), instanceOf(IncrementKeyGenerateAlgorithm.class));
}
@Test
......@@ -74,7 +75,7 @@ public final class ShardingRuleTest {
assertTrue(actual.getBroadcastTables().isEmpty());
assertThat(actual.getDefaultDatabaseShardingStrategy(), instanceOf(NoneShardingStrategy.class));
assertThat(actual.getDefaultTableShardingStrategy(), instanceOf(NoneShardingStrategy.class));
assertThat(actual.getDefaultShardingKeyGenerator(), instanceOf(SnowflakeShardingKeyGenerator.class));
assertThat(actual.getDefaultKeyGenerateAlgorithm(), instanceOf(SnowflakeKeyGenerateAlgorithm.class));
}
@Test
......@@ -397,7 +398,8 @@ public final class ShardingRuleTest {
ShardingRuleConfiguration shardingRuleConfiguration = new ShardingRuleConfiguration();
shardingRuleConfiguration.setDefaultDataSourceName("ds_0");
TableRuleConfiguration tableRuleConfiguration = createTableRuleConfiguration("LOGIC_TABLE", "ds_${0..1}.table_${0..2}");
tableRuleConfiguration.setKeyGeneratorConfig(new KeyGeneratorConfiguration("INCREMENT", "id", new Properties()));
KeyGenerateAlgorithm keyGenerateAlgorithm = new KeyGenerateAlgorithmServiceLoader().newService("INCREMENT", new Properties());
tableRuleConfiguration.setKeyGeneratorConfig(new KeyGeneratorConfiguration("id", keyGenerateAlgorithm));
TableRuleConfiguration subTableRuleConfiguration = createTableRuleConfiguration("SUB_LOGIC_TABLE", "ds_${0..1}.sub_table_${0..2}");
shardingRuleConfiguration.getTableRuleConfigs().add(tableRuleConfiguration);
shardingRuleConfiguration.getTableRuleConfigs().add(subTableRuleConfiguration);
......@@ -405,7 +407,8 @@ public final class ShardingRuleTest {
shardingRuleConfiguration.getBroadcastTables().add("BROADCAST_TABLE");
shardingRuleConfiguration.setDefaultDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("ds_id", "ds_%{ds_id % 2}"));
shardingRuleConfiguration.setDefaultTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("table_id", "table_%{table_id % 2}"));
shardingRuleConfiguration.setDefaultKeyGeneratorConfig(new KeyGeneratorConfiguration("INCREMENT", "id", new Properties()));
KeyGenerateAlgorithm defaultKeyGenerateAlgorithm = new KeyGenerateAlgorithmServiceLoader().newService("INCREMENT", new Properties());
shardingRuleConfiguration.setDefaultKeyGeneratorConfig(new KeyGeneratorConfiguration("id", defaultKeyGenerateAlgorithm));
return new ShardingRule(shardingRuleConfiguration, createDataSourceNames());
}
......
......@@ -17,29 +17,30 @@
package org.apache.shardingsphere.core.rule;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import com.google.common.collect.Sets;
import java.util.Arrays;
import java.util.Collections;
import java.util.Properties;
import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.InlineShardingStrategyConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.NoneShardingStrategyConfiguration;
import org.apache.shardingsphere.core.strategy.keygen.fixture.IncrementShardingKeyGenerator;
import org.apache.shardingsphere.core.strategy.keygen.fixture.IncrementKeyGenerateAlgorithm;
import org.apache.shardingsphere.spi.algorithm.keygen.KeyGenerateAlgorithmServiceLoader;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import org.apache.shardingsphere.underlying.common.config.exception.ShardingSphereConfigurationException;
import org.apache.shardingsphere.underlying.common.rule.DataNode;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.Properties;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public final class TableRuleTest {
@Test
......@@ -59,7 +60,8 @@ public final class TableRuleTest {
TableRuleConfiguration tableRuleConfig = new TableRuleConfiguration("LOGIC_TABLE", "ds${0..1}.table_${0..2}");
tableRuleConfig.setDatabaseShardingStrategyConfig(new NoneShardingStrategyConfiguration());
tableRuleConfig.setTableShardingStrategyConfig(new NoneShardingStrategyConfiguration());
tableRuleConfig.setKeyGeneratorConfig(new KeyGeneratorConfiguration("INCREMENT", "col_1", new Properties()));
KeyGenerateAlgorithm keyGenerateAlgorithm = new KeyGenerateAlgorithmServiceLoader().newService("INCREMENT", new Properties());
tableRuleConfig.setKeyGeneratorConfig(new KeyGeneratorConfiguration("col_1", keyGenerateAlgorithm));
TableRule actual = new TableRule(tableRuleConfig, createShardingDataSourceNames(), null);
assertThat(actual.getLogicTable(), is("logic_table"));
assertThat(actual.getActualDataNodes().size(), is(6));
......@@ -73,7 +75,7 @@ public final class TableRuleTest {
assertNotNull(actual.getTableShardingStrategy());
assertTrue(actual.getGenerateKeyColumn().isPresent());
assertThat(actual.getGenerateKeyColumn().get(), is("col_1"));
assertThat(actual.getShardingKeyGenerator(), instanceOf(IncrementShardingKeyGenerator.class));
assertThat(actual.getKeyGenerateAlgorithm(), instanceOf(IncrementKeyGenerateAlgorithm.class));
}
@Test
......
......@@ -17,30 +17,29 @@
package org.apache.shardingsphere.core.strategy.keygen;
import org.apache.shardingsphere.spi.algorithm.keygen.ShardingKeyGeneratorServiceLoader;
import org.junit.Test;
import java.util.Properties;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;
public final class ShardingKeyGeneratorServiceLoaderTest {
import java.util.Properties;
import org.apache.shardingsphere.spi.algorithm.keygen.KeyGenerateAlgorithmServiceLoader;
import org.junit.Test;
public final class KeyGenerateAlgorithmServiceLoaderTest {
private ShardingKeyGeneratorServiceLoader serviceLoader = new ShardingKeyGeneratorServiceLoader();
private KeyGenerateAlgorithmServiceLoader serviceLoader = new KeyGenerateAlgorithmServiceLoader();
@Test
public void assertNewSnowflakeKeyGenerator() {
assertThat(serviceLoader.newService("SNOWFLAKE", new Properties()), instanceOf(SnowflakeShardingKeyGenerator.class));
public void assertNewSnowflakeKeyGenerateAlgorithm() {
assertThat(serviceLoader.newService("SNOWFLAKE", new Properties()), instanceOf(SnowflakeKeyGenerateAlgorithm.class));
}
@Test
public void assertNewUUIDKeyGenerator() {
assertThat(serviceLoader.newService("UUID", new Properties()), instanceOf(UUIDShardingKeyGenerator.class));
public void assertNewUUIDKeyGenerateAlgorithm() {
assertThat(serviceLoader.newService("UUID", new Properties()), instanceOf(UUIDKeyGenerateAlgorithm.class));
}
@Test
public void assertNewDefaultKeyGenerator() {
assertThat(serviceLoader.newService(), instanceOf(SnowflakeShardingKeyGenerator.class));
public void assertNewDefaultKeyGenerateAlgorithm() {
assertThat(serviceLoader.newService(), instanceOf(SnowflakeKeyGenerateAlgorithm.class));
}
}
......@@ -17,9 +17,9 @@
package org.apache.shardingsphere.core.strategy.keygen;
import lombok.SneakyThrows;
import org.apache.shardingsphere.core.strategy.keygen.fixture.FixedTimeService;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
import java.lang.reflect.Field;
import java.util.ArrayList;
......@@ -31,12 +31,11 @@ import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import lombok.SneakyThrows;
import org.apache.shardingsphere.core.strategy.keygen.fixture.FixedTimeService;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
public final class SnowflakeShardingKeyGeneratorTest {
public final class SnowflakeKeyGenerateAlgorithmTest {
private static final long DEFAULT_SEQUENCE_BITS = 12L;
......@@ -48,76 +47,76 @@ public final class SnowflakeShardingKeyGeneratorTest {
int threadNumber = Runtime.getRuntime().availableProcessors() << 1;
ExecutorService executor = Executors.newFixedThreadPool(threadNumber);
int taskNumber = threadNumber << 2;
SnowflakeShardingKeyGenerator keyGenerator = new SnowflakeShardingKeyGenerator();
keyGenerator.setProperties(new Properties());
SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm();
keyGenerateAlgorithm.setProperties(new Properties());
Set<Comparable<?>> actual = new HashSet<>();
for (int i = 0; i < taskNumber; i++) {
actual.add(executor.submit((Callable<Comparable<?>>) keyGenerator::generateKey).get());
actual.add(executor.submit((Callable<Comparable<?>>) keyGenerateAlgorithm::generateKey).get());
}
assertThat(actual.size(), is(taskNumber));
}
@Test
public void assertGenerateKeyWithSingleThread() {
SnowflakeShardingKeyGenerator keyGenerator = new SnowflakeShardingKeyGenerator();
keyGenerator.setProperties(new Properties());
SnowflakeShardingKeyGenerator.setTimeService(new FixedTimeService(1));
SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm();
keyGenerateAlgorithm.setProperties(new Properties());
SnowflakeKeyGenerateAlgorithm.setTimeService(new FixedTimeService(1));
List<Comparable<?>> expected = Arrays.asList(0L, 4194305L, 4194306L, 8388608L, 8388609L, 12582913L, 12582914L, 16777216L, 16777217L, 20971521L);
List<Comparable<?>> actual = new ArrayList<>();
for (int i = 0; i < DEFAULT_KEY_AMOUNT; i++) {
actual.add(keyGenerator.generateKey());
actual.add(keyGenerateAlgorithm.generateKey());
}
assertThat(actual, is(expected));
}
@Test
public void assertLastDigitalOfGenerateKeySameMillisecond() {
SnowflakeShardingKeyGenerator keyGenerator = new SnowflakeShardingKeyGenerator();
SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm();
Properties properties = new Properties();
SnowflakeShardingKeyGenerator.setTimeService(new FixedTimeService(5));
SnowflakeKeyGenerateAlgorithm.setTimeService(new FixedTimeService(5));
properties.setProperty("max.vibration.offset", String.valueOf(3));
keyGenerator.setProperties(properties);
assertThat(keyGenerator.generateKey(), is((Comparable) 0L));
assertThat(keyGenerator.generateKey(), is((Comparable) 1L));
assertThat(keyGenerator.generateKey(), is((Comparable) 2L));
assertThat(keyGenerator.generateKey(), is((Comparable) 3L));
assertThat(keyGenerator.generateKey(), is((Comparable) 4L));
keyGenerateAlgorithm.setProperties(properties);
assertThat(keyGenerateAlgorithm.generateKey(), is((Comparable) 0L));
assertThat(keyGenerateAlgorithm.generateKey(), is((Comparable) 1L));
assertThat(keyGenerateAlgorithm.generateKey(), is((Comparable) 2L));
assertThat(keyGenerateAlgorithm.generateKey(), is((Comparable) 3L));
assertThat(keyGenerateAlgorithm.generateKey(), is((Comparable) 4L));
}
@Test
public void assertLastDigitalOfGenerateKeyDifferentMillisecond() throws InterruptedException {
SnowflakeShardingKeyGenerator keyGenerator = new SnowflakeShardingKeyGenerator();
SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm();
Properties properties = new Properties();
SnowflakeShardingKeyGenerator.setTimeService(new TimeService());
SnowflakeKeyGenerateAlgorithm.setTimeService(new TimeService());
properties.setProperty("max.vibration.offset", String.valueOf(3));
keyGenerator.setProperties(properties);
String actualGenerateKeyBinaryString0 = Long.toBinaryString(Long.parseLong(keyGenerator.generateKey().toString()));
keyGenerateAlgorithm.setProperties(properties);
String actualGenerateKeyBinaryString0 = Long.toBinaryString(Long.parseLong(keyGenerateAlgorithm.generateKey().toString()));
assertThat(Integer.parseInt(actualGenerateKeyBinaryString0.substring(actualGenerateKeyBinaryString0.length() - 3), 2), is(0));
Thread.sleep(2L);
String actualGenerateKeyBinaryString1 = Long.toBinaryString(Long.parseLong(keyGenerator.generateKey().toString()));
String actualGenerateKeyBinaryString1 = Long.toBinaryString(Long.parseLong(keyGenerateAlgorithm.generateKey().toString()));
assertThat(Integer.parseInt(actualGenerateKeyBinaryString1.substring(actualGenerateKeyBinaryString1.length() - 3), 2), is(1));
Thread.sleep(2L);
String actualGenerateKeyBinaryString2 = Long.toBinaryString(Long.parseLong(keyGenerator.generateKey().toString()));
String actualGenerateKeyBinaryString2 = Long.toBinaryString(Long.parseLong(keyGenerateAlgorithm.generateKey().toString()));
assertThat(Integer.parseInt(actualGenerateKeyBinaryString2.substring(actualGenerateKeyBinaryString2.length() - 3), 2), is(2));
Thread.sleep(2L);
String actualGenerateKeyBinaryString3 = Long.toBinaryString(Long.parseLong(keyGenerator.generateKey().toString()));
String actualGenerateKeyBinaryString3 = Long.toBinaryString(Long.parseLong(keyGenerateAlgorithm.generateKey().toString()));
assertThat(Integer.parseInt(actualGenerateKeyBinaryString3.substring(actualGenerateKeyBinaryString3.length() - 3), 2), is(3));
Thread.sleep(2L);
String actualGenerateKeyBinaryString4 = Long.toBinaryString(Long.parseLong(keyGenerator.generateKey().toString()));
String actualGenerateKeyBinaryString4 = Long.toBinaryString(Long.parseLong(keyGenerateAlgorithm.generateKey().toString()));
assertThat(Integer.parseInt(actualGenerateKeyBinaryString4.substring(actualGenerateKeyBinaryString4.length() - 3), 2), is(0));
}
@Test
public void assertGenerateKeyWithClockCallBack() {
SnowflakeShardingKeyGenerator keyGenerator = new SnowflakeShardingKeyGenerator();
SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm();
TimeService timeService = new FixedTimeService(1);
SnowflakeShardingKeyGenerator.setTimeService(timeService);
keyGenerator.setProperties(new Properties());
setLastMilliseconds(keyGenerator, timeService.getCurrentMillis() + 2);
SnowflakeKeyGenerateAlgorithm.setTimeService(timeService);
keyGenerateAlgorithm.setProperties(new Properties());
setLastMilliseconds(keyGenerateAlgorithm, timeService.getCurrentMillis() + 2);
List<Comparable<?>> expected = Arrays.asList(4194304L, 8388609L, 8388610L, 12582912L, 12582913L, 16777217L, 16777218L, 20971520L, 20971521L, 25165825L);
List<Comparable<?>> actual = new ArrayList<>();
for (int i = 0; i < DEFAULT_KEY_AMOUNT; i++) {
actual.add(keyGenerator.generateKey());
actual.add(keyGenerateAlgorithm.generateKey());
}
assertThat(actual, is(expected));
}
......@@ -125,108 +124,108 @@ public final class SnowflakeShardingKeyGeneratorTest {
@Test(expected = IllegalStateException.class)
@SneakyThrows
public void assertGenerateKeyWithClockCallBackBeyondTolerateTime() {
SnowflakeShardingKeyGenerator keyGenerator = new SnowflakeShardingKeyGenerator();
SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm();
TimeService timeService = new FixedTimeService(1);
SnowflakeShardingKeyGenerator.setTimeService(timeService);
keyGenerator.setProperties(new Properties());
SnowflakeKeyGenerateAlgorithm.setTimeService(timeService);
keyGenerateAlgorithm.setProperties(new Properties());
Properties properties = new Properties();
properties.setProperty("max.tolerate.time.difference.milliseconds", String.valueOf(0));
keyGenerator.setProperties(properties);
setLastMilliseconds(keyGenerator, timeService.getCurrentMillis() + 2);
keyGenerateAlgorithm.setProperties(properties);
setLastMilliseconds(keyGenerateAlgorithm, timeService.getCurrentMillis() + 2);
List<Comparable<?>> actual = new ArrayList<>();
for (int i = 0; i < DEFAULT_KEY_AMOUNT; i++) {
actual.add(keyGenerator.generateKey());
actual.add(keyGenerateAlgorithm.generateKey());
}
assertNotEquals(actual.size(), 10);
}
@Test
public void assertGenerateKeyBeyondMaxSequencePerMilliSecond() {
final SnowflakeShardingKeyGenerator keyGenerator = new SnowflakeShardingKeyGenerator();
final SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm();
TimeService timeService = new FixedTimeService(2);
SnowflakeShardingKeyGenerator.setTimeService(timeService);
keyGenerator.setProperties(new Properties());
setLastMilliseconds(keyGenerator, timeService.getCurrentMillis());
setSequence(keyGenerator, (1 << DEFAULT_SEQUENCE_BITS) - 1);
SnowflakeKeyGenerateAlgorithm.setTimeService(timeService);
keyGenerateAlgorithm.setProperties(new Properties());
setLastMilliseconds(keyGenerateAlgorithm, timeService.getCurrentMillis());
setSequence(keyGenerateAlgorithm, (1 << DEFAULT_SEQUENCE_BITS) - 1);
List<Comparable<?>> expected = Arrays.asList(4194304L, 4194305L, 4194306L, 8388608L, 8388609L, 8388610L, 12582913L, 12582914L, 12582915L, 16777216L);
List<Comparable<?>> actual = new ArrayList<>();
for (int i = 0; i < DEFAULT_KEY_AMOUNT; i++) {
actual.add(keyGenerator.generateKey());
actual.add(keyGenerateAlgorithm.generateKey());
}
assertThat(actual, is(expected));
}
@SneakyThrows
private void setSequence(final SnowflakeShardingKeyGenerator keyGenerator, final Number value) {
Field sequence = SnowflakeShardingKeyGenerator.class.getDeclaredField("sequence");
private void setSequence(final SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm, final Number value) {
Field sequence = SnowflakeKeyGenerateAlgorithm.class.getDeclaredField("sequence");
sequence.setAccessible(true);
sequence.set(keyGenerator, value);
sequence.set(keyGenerateAlgorithm, value);
}
@SneakyThrows
private void setLastMilliseconds(final SnowflakeShardingKeyGenerator keyGenerator, final Number value) {
Field lastMilliseconds = SnowflakeShardingKeyGenerator.class.getDeclaredField("lastMilliseconds");
private void setLastMilliseconds(final SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm, final Number value) {
Field lastMilliseconds = SnowflakeKeyGenerateAlgorithm.class.getDeclaredField("lastMilliseconds");
lastMilliseconds.setAccessible(true);
lastMilliseconds.set(keyGenerator, value);
lastMilliseconds.set(keyGenerateAlgorithm, value);
}
@Test(expected = IllegalArgumentException.class)
public void assertSetWorkerIdFailureWhenNegative() {
SnowflakeShardingKeyGenerator keyGenerator = new SnowflakeShardingKeyGenerator();
SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm();
Properties properties = new Properties();
properties.setProperty("worker.id", String.valueOf(-1L));
keyGenerator.setProperties(properties);
keyGenerator.generateKey();
keyGenerateAlgorithm.setProperties(properties);
keyGenerateAlgorithm.generateKey();
}
@Test(expected = IllegalArgumentException.class)
public void assertSetMaxVibrationOffsetFailureWhenNegative() {
SnowflakeShardingKeyGenerator keyGenerator = new SnowflakeShardingKeyGenerator();
SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm();
Properties properties = new Properties();
properties.setProperty("max.vibration.offset", String.valueOf(-1));
keyGenerator.setProperties(properties);
keyGenerator.generateKey();
keyGenerateAlgorithm.setProperties(properties);
keyGenerateAlgorithm.generateKey();
}
@Test(expected = IllegalArgumentException.class)
public void assertSetWorkerIdFailureWhenOutOfRange() {
SnowflakeShardingKeyGenerator keyGenerator = new SnowflakeShardingKeyGenerator();
SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm();
Properties properties = new Properties();
properties.setProperty("worker.id", String.valueOf(Long.MIN_VALUE));
keyGenerator.setProperties(properties);
keyGenerator.generateKey();
keyGenerateAlgorithm.setProperties(properties);
keyGenerateAlgorithm.generateKey();
}
@Test(expected = IllegalArgumentException.class)
public void assertSetMaxVibrationOffsetFailureWhenOutOfRange() {
SnowflakeShardingKeyGenerator keyGenerator = new SnowflakeShardingKeyGenerator();
SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm();
Properties properties = new Properties();
properties.setProperty("max.vibration.offset", String.valueOf(4096));
keyGenerator.setProperties(properties);
keyGenerator.generateKey();
keyGenerateAlgorithm.setProperties(properties);
keyGenerateAlgorithm.generateKey();
}
@Test
@SneakyThrows
public void assertSetWorkerIdSuccess() {
SnowflakeShardingKeyGenerator keyGenerator = new SnowflakeShardingKeyGenerator();
SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm();
Properties properties = new Properties();
properties.setProperty("worker.id", String.valueOf(1L));
keyGenerator.setProperties(properties);
Field props = keyGenerator.getClass().getDeclaredField("properties");
keyGenerateAlgorithm.setProperties(properties);
Field props = keyGenerateAlgorithm.getClass().getDeclaredField("properties");
props.setAccessible(true);
assertThat(((Properties) props.get(keyGenerator)).get("worker.id"), is("1"));
assertThat(((Properties) props.get(keyGenerateAlgorithm)).get("worker.id"), is("1"));
}
@Test
@SneakyThrows
public void assertSetMaxTolerateTimeDifferenceMilliseconds() {
SnowflakeShardingKeyGenerator keyGenerator = new SnowflakeShardingKeyGenerator();
SnowflakeKeyGenerateAlgorithm keyGenerateAlgorithm = new SnowflakeKeyGenerateAlgorithm();
Properties properties = new Properties();
properties.setProperty("max.tolerate.time.difference.milliseconds", String.valueOf(1));
keyGenerator.setProperties(properties);
Field props = keyGenerator.getClass().getDeclaredField("properties");
keyGenerateAlgorithm.setProperties(properties);
Field props = keyGenerateAlgorithm.getClass().getDeclaredField("properties");
props.setAccessible(true);
assertThat(((Properties) props.get(keyGenerator)).get("max.tolerate.time.difference.milliseconds"), is("1"));
assertThat(((Properties) props.get(keyGenerateAlgorithm)).get("max.tolerate.time.difference.milliseconds"), is("1"));
}
}
......@@ -17,32 +17,31 @@
package org.apache.shardingsphere.core.strategy.keygen;
import org.junit.Test;
import java.util.Properties;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public final class UUIDShardingKeyGeneratorTest {
import java.util.Properties;
import org.junit.Test;
public final class UUIDKeyGenerateAlgorithmTest {
private UUIDShardingKeyGenerator uuidKeyGenerator = new UUIDShardingKeyGenerator();
private UUIDKeyGenerateAlgorithm uuidKeyGenerateAlgorithm = new UUIDKeyGenerateAlgorithm();
@Test
public void assertGenerateKey() {
assertThat(((String) uuidKeyGenerator.generateKey()).length(), is(32));
assertThat(((String) uuidKeyGenerateAlgorithm.generateKey()).length(), is(32));
}
@Test
public void assertGetProperties() {
assertThat(uuidKeyGenerator.getProperties().entrySet().size(), is(0));
assertThat(uuidKeyGenerateAlgorithm.getProperties().entrySet().size(), is(0));
}
@Test
public void assertSetProperties() {
Properties properties = new Properties();
properties.setProperty("key1", "value1");
uuidKeyGenerator.setProperties(properties);
assertThat(uuidKeyGenerator.getProperties().get("key1"), is("value1"));
uuidKeyGenerateAlgorithm.setProperties(properties);
assertThat(uuidKeyGenerateAlgorithm.getProperties().get("key1"), is("value1"));
}
}
......@@ -18,7 +18,7 @@
package org.apache.shardingsphere.core.strategy.keygen.fixture;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator;
import org.apache.shardingsphere.core.strategy.keygen.SnowflakeKeyGenerateAlgorithm;
import org.apache.shardingsphere.core.strategy.keygen.TimeService;
import java.util.concurrent.atomic.AtomicInteger;
......@@ -30,7 +30,7 @@ public final class FixedTimeService extends TimeService {
private final AtomicInteger invokedTimes = new AtomicInteger();
private long current = SnowflakeShardingKeyGenerator.EPOCH;
private long current = SnowflakeKeyGenerateAlgorithm.EPOCH;
@Override
public long getCurrentMillis() {
......
......@@ -19,12 +19,12 @@ package org.apache.shardingsphere.core.strategy.keygen.fixture;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
public final class IncrementShardingKeyGenerator implements ShardingKeyGenerator {
public final class IncrementKeyGenerateAlgorithm implements KeyGenerateAlgorithm {
@Getter
private final String type = "INCREMENT";
......
......@@ -17,20 +17,22 @@
package org.apache.shardingsphere.core.yaml.swapper;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Properties;
import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.core.yaml.config.sharding.YamlKeyGeneratorConfiguration;
import org.apache.shardingsphere.spi.algorithm.keygen.KeyGenerateAlgorithmServiceLoader;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import org.junit.Test;
import java.util.Properties;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public final class KeyGeneratorConfigurationYamlSwapperTest {
@Test
public void assertSwapToYaml() {
YamlKeyGeneratorConfiguration actual = new KeyGeneratorConfigurationYamlSwapper().swap(new KeyGeneratorConfiguration("UUID", "id", new Properties()));
KeyGenerateAlgorithm keyGenerateAlgorithm = new KeyGenerateAlgorithmServiceLoader().newService("UUID", new Properties());
YamlKeyGeneratorConfiguration actual = new KeyGeneratorConfigurationYamlSwapper().swap(new KeyGeneratorConfiguration("id", keyGenerateAlgorithm));
assertThat(actual.getType(), is("UUID"));
assertThat(actual.getColumn(), is("id"));
assertThat(actual.getProps(), is(new Properties()));
......@@ -42,8 +44,8 @@ public final class KeyGeneratorConfigurationYamlSwapperTest {
yamlConfiguration.setType("UUID");
yamlConfiguration.setColumn("id");
KeyGeneratorConfiguration actual = new KeyGeneratorConfigurationYamlSwapper().swap(yamlConfiguration);
assertThat(actual.getType(), is("UUID"));
assertThat(actual.getKeyGenerateAlgorithm().getType(), is("UUID"));
assertThat(actual.getColumn(), is("id"));
assertThat(actual.getProperties(), is(new Properties()));
assertThat(actual.getKeyGenerateAlgorithm().getProperties(), is(new Properties()));
}
}
......@@ -15,6 +15,6 @@
# limitations under the License.
#
org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator
org.apache.shardingsphere.core.strategy.keygen.UUIDShardingKeyGenerator
org.apache.shardingsphere.core.strategy.keygen.fixture.IncrementShardingKeyGenerator
org.apache.shardingsphere.core.strategy.keygen.SnowflakeKeyGenerateAlgorithm
org.apache.shardingsphere.core.strategy.keygen.UUIDKeyGenerateAlgorithm
org.apache.shardingsphere.core.strategy.keygen.fixture.IncrementKeyGenerateAlgorithm
......@@ -19,13 +19,13 @@ package org.apache.shardingsphere.sharding.rewrite.fixture;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import java.util.Properties;
@Getter
@Setter
public final class ShardingKeyGeneratorFixture implements ShardingKeyGenerator {
public final class KeyGenerateAlgorithmFixture implements KeyGenerateAlgorithm {
private Properties properties = new Properties();
......
......@@ -15,4 +15,4 @@
# limitations under the License.
#
org.apache.shardingsphere.sharding.rewrite.fixture.ShardingKeyGeneratorFixture
org.apache.shardingsphere.sharding.rewrite.fixture.KeyGenerateAlgorithmFixture
......@@ -19,11 +19,11 @@ package org.apache.shardingsphere.dbtest.fixture;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import java.util.Properties;
public final class ConstantShardingKeyGenerator implements ShardingKeyGenerator {
public final class ConstantKeyGenerateAlgorithm implements KeyGenerateAlgorithm {
@Getter
private final String type = "CONSTANT";
......
......@@ -19,12 +19,12 @@ package org.apache.shardingsphere.shardingjdbc.fixture;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
public final class IncrementShardingKeyGenerator implements ShardingKeyGenerator {
public final class IncrementKeyGenerateAlgorithm implements KeyGenerateAlgorithm {
@Getter
private final String type = "INCREMENT";
......
......@@ -15,6 +15,6 @@
# limitations under the License.
#
org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator
org.apache.shardingsphere.core.strategy.keygen.UUIDShardingKeyGenerator
org.apache.shardingsphere.shardingjdbc.fixture.IncrementShardingKeyGenerator
org.apache.shardingsphere.core.strategy.keygen.SnowflakeKeyGenerateAlgorithm
org.apache.shardingsphere.core.strategy.keygen.UUIDKeyGenerateAlgorithm
org.apache.shardingsphere.shardingjdbc.fixture.IncrementKeyGenerateAlgorithm
......@@ -19,12 +19,12 @@ package org.apache.shardingsphere.shardingjdbc.orchestration.api.yaml.fixture;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
public final class DecrementShardingKeyGenerator implements ShardingKeyGenerator {
public final class DecrementKeyGenerateAlgorithm implements KeyGenerateAlgorithm {
@Getter
private final String type = "DECREMENT";
......
......@@ -19,12 +19,12 @@ package org.apache.shardingsphere.shardingjdbc.orchestration.api.yaml.fixture;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
public final class IncrementShardingKeyGenerator implements ShardingKeyGenerator {
public final class IncrementKeyGenerateAlgorithm implements KeyGenerateAlgorithm {
private static final AtomicInteger SEQUENCE = new AtomicInteger(100);
......
......@@ -15,7 +15,7 @@
# limitations under the License.
#
org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator
org.apache.shardingsphere.core.strategy.keygen.UUIDShardingKeyGenerator
org.apache.shardingsphere.shardingjdbc.orchestration.api.yaml.fixture.DecrementShardingKeyGenerator
org.apache.shardingsphere.shardingjdbc.orchestration.api.yaml.fixture.IncrementShardingKeyGenerator
org.apache.shardingsphere.core.strategy.keygen.SnowflakeKeyGenerateAlgorithm
org.apache.shardingsphere.core.strategy.keygen.UUIDKeyGenerateAlgorithm
org.apache.shardingsphere.shardingjdbc.orchestration.api.yaml.fixture.DecrementKeyGenerateAlgorithm
org.apache.shardingsphere.shardingjdbc.orchestration.api.yaml.fixture.IncrementKeyGenerateAlgorithm
......@@ -17,11 +17,18 @@
package org.apache.shardingsphere.shardingjdbc.orchestration.spring;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.shardingsphere.core.rule.ShardingRule;
import org.apache.shardingsphere.core.strategy.masterslave.RoundRobinMasterSlaveLoadBalanceAlgorithm;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.spring.datasource.OrchestrationSpringShardingDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.spring.fixture.IncrementKeyGenerator;
import org.apache.shardingsphere.shardingjdbc.orchestration.spring.fixture.IncrementKeyGenerateAlgorithm;
import org.apache.shardingsphere.shardingjdbc.orchestration.spring.util.EmbedTestingServer;
import org.apache.shardingsphere.shardingjdbc.orchestration.spring.util.FieldValueUtil;
import org.junit.BeforeClass;
......@@ -29,14 +36,6 @@ import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import javax.sql.DataSource;
import java.util.Map;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
@ContextConfiguration(locations = "classpath:META-INF/rdb/shardingMasterSlaveOrchestration.xml")
public class OrchestrationShardingMasterSlaveNamespaceTest extends AbstractJUnit4SpringContextTests {
......@@ -70,7 +69,7 @@ public class OrchestrationShardingMasterSlaveNamespaceTest extends AbstractJUnit
assertThat(shardingRule.getMasterSlaveRules().iterator().next().getLoadBalanceAlgorithm(), instanceOf(RoundRobinMasterSlaveLoadBalanceAlgorithm.class));
assertThat(shardingRule.getTableRules().size(), is(1));
assertThat(shardingRule.getTableRules().iterator().next().getLogicTable(), is("t_order"));
assertThat(shardingRule.getDefaultShardingKeyGenerator(), instanceOf(IncrementKeyGenerator.class));
assertThat(shardingRule.getDefaultKeyGenerateAlgorithm(), instanceOf(IncrementKeyGenerateAlgorithm.class));
}
@SuppressWarnings("unchecked")
......
......@@ -17,35 +17,34 @@
package org.apache.shardingsphere.shardingjdbc.orchestration.spring;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.shardingsphere.api.config.sharding.strategy.InlineShardingStrategyConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.StandardShardingStrategyConfiguration;
import org.apache.shardingsphere.core.rule.BindingTableRule;
import org.apache.shardingsphere.underlying.common.rule.DataNode;
import org.apache.shardingsphere.core.rule.ShardingRule;
import org.apache.shardingsphere.core.rule.TableRule;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.spring.datasource.OrchestrationSpringShardingDataSource;
import org.apache.shardingsphere.shardingjdbc.orchestration.spring.fixture.IncrementKeyGenerator;
import org.apache.shardingsphere.shardingjdbc.orchestration.spring.fixture.IncrementKeyGenerateAlgorithm;
import org.apache.shardingsphere.shardingjdbc.orchestration.spring.util.EmbedTestingServer;
import org.apache.shardingsphere.shardingjdbc.orchestration.spring.util.FieldValueUtil;
import org.apache.shardingsphere.underlying.common.config.properties.ConfigurationPropertyKey;
import org.apache.shardingsphere.underlying.common.config.properties.ConfigurationProperties;
import org.apache.shardingsphere.underlying.common.config.properties.ConfigurationPropertyKey;
import org.apache.shardingsphere.underlying.common.rule.DataNode;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import static org.hamcrest.CoreMatchers.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/shardingOrchestration.xml")
public class OrchestrationShardingNamespaceTest extends AbstractJUnit4SpringContextTests {
......@@ -74,7 +73,7 @@ public class OrchestrationShardingNamespaceTest extends AbstractJUnit4SpringCont
new String[]{applicationContext.getBean("standardStrategy", StandardShardingStrategyConfiguration.class).getShardingColumn()}));
assertTrue(Arrays.equals(shardingRule.getDefaultTableShardingStrategy().getShardingColumns().toArray(new String[]{}),
new String[]{applicationContext.getBean("inlineStrategy", InlineShardingStrategyConfiguration.class).getShardingColumn()}));
assertThat(shardingRule.getDefaultShardingKeyGenerator().getClass().getName(), is(IncrementKeyGenerator.class.getCanonicalName()));
assertThat(shardingRule.getDefaultKeyGenerateAlgorithm().getClass().getName(), is(IncrementKeyGenerateAlgorithm.class.getCanonicalName()));
}
@Test
......@@ -98,7 +97,7 @@ public class OrchestrationShardingNamespaceTest extends AbstractJUnit4SpringCont
new String[]{applicationContext.getBean("inlineStrategy", InlineShardingStrategyConfiguration.class).getShardingColumn()}));
assertTrue(tableRule.getGenerateKeyColumn().isPresent());
assertThat(tableRule.getGenerateKeyColumn().get(), is("order_id"));
assertThat(tableRule.getShardingKeyGenerator().getClass().getName(), is(IncrementKeyGenerator.class.getCanonicalName()));
assertThat(tableRule.getKeyGenerateAlgorithm().getClass().getName(), is(IncrementKeyGenerateAlgorithm.class.getCanonicalName()));
}
@Test
......
......@@ -19,12 +19,12 @@ package org.apache.shardingsphere.shardingjdbc.orchestration.spring.fixture;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
public final class DecrementKeyGenerator implements ShardingKeyGenerator {
public final class DecrementKeyGenerateAlgorithm implements KeyGenerateAlgorithm {
@Getter
@Setter
......
......@@ -19,12 +19,12 @@ package org.apache.shardingsphere.shardingjdbc.orchestration.spring.fixture;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
public final class IncrementKeyGenerator implements ShardingKeyGenerator {
public final class IncrementKeyGenerateAlgorithm implements KeyGenerateAlgorithm {
@Getter
@Setter
......
......@@ -31,6 +31,9 @@
<bean id="rangeModuloTableShardingAlgorithm" class="org.apache.shardingsphere.shardingjdbc.orchestration.spring.algorithm.RangeModuloTableShardingAlgorithm" />
<bean id="defaultComplexKeysShardingAlgorithm" class="org.apache.shardingsphere.shardingjdbc.orchestration.spring.algorithm.DefaultComplexKeysShardingAlgorithm" />
<bean id="defaultHintShardingAlgorithm" class="org.apache.shardingsphere.shardingjdbc.orchestration.spring.algorithm.DefaultHintShardingAlgorithm" />
<bean id="incrementAlgorithm" class="org.apache.shardingsphere.shardingjdbc.spring.namespace.factorybean.KeyGenerateAlgorithmFactoryBean">
<property name="type" value="INCREMENT" />
</bean>
<sharding:standard-strategy id="standardStrategy" sharding-column="user_id" precise-algorithm-ref="preciseModuloDatabaseShardingAlgorithm" />
<sharding:standard-strategy id="rangeStandardStrategy" sharding-column="order_id" precise-algorithm-ref="preciseModuloTableShardingAlgorithm" range-algorithm-ref="rangeModuloTableShardingAlgorithm" />
......@@ -39,7 +42,7 @@
<sharding:hint-strategy id="hintStrategy" algorithm-ref="defaultHintShardingAlgorithm" />
<sharding:none-strategy id="noneStrategy" />
<sharding:key-generator id="keyGenerator" type="INCREMENT" column="order_id" />
<sharding:key-generator id="keyGenerator" column="order_id" algorithm-ref="incrementAlgorithm" />
<sharding:data-source id="simpleShardingDataSource">
<sharding:sharding-rule data-source-names="dbtbl_0">
......
......@@ -35,6 +35,9 @@
<bean id="rangeModuloTableShardingAlgorithm" class="org.apache.shardingsphere.shardingjdbc.orchestration.spring.algorithm.RangeModuloTableShardingAlgorithm" />
<bean id="defaultComplexKeysShardingAlgorithm" class="org.apache.shardingsphere.shardingjdbc.orchestration.spring.algorithm.DefaultComplexKeysShardingAlgorithm" />
<bean id="defaultHintShardingAlgorithm" class="org.apache.shardingsphere.shardingjdbc.orchestration.spring.algorithm.DefaultHintShardingAlgorithm" />
<bean id="incrementAlgorithm" class="org.apache.shardingsphere.shardingjdbc.spring.namespace.factorybean.KeyGenerateAlgorithmFactoryBean">
<property name="type" value="INCREMENT" />
</bean>
<sharding:standard-strategy id="standardStrategy" sharding-column="user_id" precise-algorithm-ref="preciseModuloDatabaseShardingAlgorithm" />
<sharding:standard-strategy id="rangeStandardStrategy" sharding-column="order_id" precise-algorithm-ref="preciseModuloTableShardingAlgorithm" range-algorithm-ref="rangeModuloTableShardingAlgorithm" />
......@@ -42,7 +45,7 @@
<sharding:hint-strategy id="hintStrategy" algorithm-ref="defaultHintShardingAlgorithm" />
<sharding:none-strategy id="noneStrategy" />
<sharding:key-generator id="keyGenerator" type="INCREMENT" column="order_id" />
<sharding:key-generator id="keyGenerator" column="order_id" algorithm-ref="incrementAlgorithm" />
<master-slave:load-balance-algorithm id="randomLoadBalanceAlgorithm" type="RANDOM"/>
<sharding:data-source id="masterSlaveShardingDataSourceByDefaultStrategy">
......
......@@ -15,5 +15,5 @@
# limitations under the License.
#
org.apache.shardingsphere.shardingjdbc.orchestration.spring.fixture.DecrementKeyGenerator
org.apache.shardingsphere.shardingjdbc.orchestration.spring.fixture.IncrementKeyGenerator
org.apache.shardingsphere.shardingjdbc.orchestration.spring.fixture.DecrementKeyGenerateAlgorithm
org.apache.shardingsphere.shardingjdbc.orchestration.spring.fixture.IncrementKeyGenerateAlgorithm
......@@ -76,9 +76,7 @@ public final class ShardingDataSourceBeanDefinitionParserTag {
public static final String GENERATE_KEY_COLUMN_ATTRIBUTE = "column";
public static final String GENERATE_KEY_TYPE_ATTRIBUTE = "type";
public static final String GENERATE_KEY_PROPERTY_REF_ATTRIBUTE = "props-ref";
public static final String GENERATE_KEY_ALGORITHM_REF_TAG = "algorithm-ref";
public static final String LOGIC_INDEX = "logic-index";
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.spring.namespace.factorybean;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import java.util.Properties;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.spi.algorithm.keygen.KeyGenerateAlgorithmServiceLoader;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
/**
* key generate algorithm FactoryBean.
*/
@Setter
@Getter
public class KeyGenerateAlgorithmFactoryBean implements FactoryBean<KeyGenerateAlgorithm>, InitializingBean {
private String type;
private Properties properties;
@Override
public KeyGenerateAlgorithm getObject() throws Exception {
return new KeyGenerateAlgorithmServiceLoader().newService(type, properties);
}
@Override
public Class<?> getObjectType() {
return KeyGenerateAlgorithm.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public void afterPropertiesSet() throws Exception {
Preconditions.checkArgument(!Strings.isNullOrEmpty(type), "The type of keyGenerateAlgorithm is required.");
}
}
......@@ -17,17 +17,14 @@
package org.apache.shardingsphere.shardingjdbc.spring.namespace.parser;
import com.google.common.base.Strings;
import org.apache.shardingsphere.shardingjdbc.spring.namespace.constants.ShardingDataSourceBeanDefinitionParserTag;
import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.shardingjdbc.spring.namespace.constants.ShardingDataSourceBeanDefinitionParserTag;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;
import java.util.Properties;
/**
* Key generator bean parser for spring namespace.
*/
......@@ -36,18 +33,8 @@ public final class KeyGeneratorBeanDefinitionParser extends AbstractBeanDefiniti
@Override
protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(KeyGeneratorConfiguration.class);
factory.addConstructorArgValue(element.getAttribute(ShardingDataSourceBeanDefinitionParserTag.GENERATE_KEY_TYPE_ATTRIBUTE));
factory.addConstructorArgValue(element.getAttribute(ShardingDataSourceBeanDefinitionParserTag.GENERATE_KEY_COLUMN_ATTRIBUTE));
parseProperties(element, factory);
factory.addConstructorArgReference(element.getAttribute(ShardingDataSourceBeanDefinitionParserTag.GENERATE_KEY_ALGORITHM_REF_TAG));
return factory.getBeanDefinition();
}
private void parseProperties(final Element element, final BeanDefinitionBuilder factory) {
String properties = element.getAttribute(ShardingDataSourceBeanDefinitionParserTag.GENERATE_KEY_PROPERTY_REF_ATTRIBUTE);
if (!Strings.isNullOrEmpty(properties)) {
factory.addConstructorArgReference(properties);
} else {
factory.addConstructorArgValue(new Properties());
}
}
}
......@@ -144,8 +144,7 @@
<xsd:complexType>
<xsd:attribute name="id" type="xsd:string" use="required" />
<xsd:attribute name="column" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="props-ref" type="xsd:string" />
<xsd:attribute name="algorithm-ref" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="props">
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.shardingsphere.shardingjdbc.spring;
import static org.junit.Assert.assertEquals;
import org.apache.shardingsphere.shardingjdbc.spring.fixture.IncrementKeyGenerateAlgorithm;
import org.apache.shardingsphere.shardingjdbc.spring.namespace.factorybean.KeyGenerateAlgorithmFactoryBean;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
@ContextConfiguration(locations = "classpath:META-INF/rdb/datasource/dataSource.xml")
public final class GenerateKeyAlgorithmTest extends AbstractJUnit4SpringContextTests {
@Test(expected = BeanCreationException.class)
public void assertTypelessKeyGenerateAlgorithm() {
GenericApplicationContext context = (GenericApplicationContext) applicationContext;
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(KeyGenerateAlgorithmFactoryBean.class);
BeanDefinition beanDefinition = builder.getBeanDefinition();
context.registerBeanDefinition("typelessAlgorithm", beanDefinition);
context.getBean("typelessAlgorithm");
}
@Test
public void assertKeyGenerateAlgorithm() {
GenericApplicationContext context = (GenericApplicationContext) applicationContext;
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(KeyGenerateAlgorithmFactoryBean.class).addPropertyValue("type", "INCREMENT");
BeanDefinition beanDefinition = builder.getBeanDefinition();
context.registerBeanDefinition("incrementAlgorithm", beanDefinition);
KeyGenerateAlgorithm incrementKeyGenerateAlgorithm = (KeyGenerateAlgorithm) context.getBean("incrementAlgorithm");
KeyGenerateAlgorithm directIncrementKeyGenerateAlgorithm = new IncrementKeyGenerateAlgorithm();
assertEquals(incrementKeyGenerateAlgorithm.generateKey(), directIncrementKeyGenerateAlgorithm.generateKey());
}
}
......@@ -17,29 +17,28 @@
package org.apache.shardingsphere.shardingjdbc.spring;
import org.apache.shardingsphere.core.rule.ShardingRule;
import org.apache.shardingsphere.core.rule.TableRule;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.context.ShardingRuntimeContext;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
import org.apache.shardingsphere.shardingjdbc.spring.fixture.DecrementKeyGenerator;
import org.apache.shardingsphere.shardingjdbc.spring.fixture.IncrementKeyGenerator;
import org.apache.shardingsphere.shardingjdbc.spring.util.FieldValueUtil;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
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.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import javax.annotation.Resource;
import org.apache.shardingsphere.core.rule.ShardingRule;
import org.apache.shardingsphere.core.rule.TableRule;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.context.ShardingRuntimeContext;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
import org.apache.shardingsphere.shardingjdbc.spring.fixture.DecrementKeyGenerateAlgorithm;
import org.apache.shardingsphere.shardingjdbc.spring.fixture.IncrementKeyGenerateAlgorithm;
import org.apache.shardingsphere.shardingjdbc.spring.util.FieldValueUtil;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(locations = "classpath:META-INF/rdb/withNamespaceGenerateKeyColumns.xml")
public class GenerateKeyJUnitTest extends AbstractSpringJUnitTest {
......@@ -69,9 +68,9 @@ public class GenerateKeyJUnitTest extends AbstractSpringJUnitTest {
assertNotNull(runtimeContext);
ShardingRule shardingRule = runtimeContext.getRule();
assertNotNull(shardingRule);
ShardingKeyGenerator defaultKeyGenerator = shardingRule.getDefaultShardingKeyGenerator();
assertNotNull(defaultKeyGenerator);
assertTrue(defaultKeyGenerator instanceof IncrementKeyGenerator);
KeyGenerateAlgorithm defaultKeyGenerateAlgorithm = shardingRule.getDefaultKeyGenerateAlgorithm();
assertNotNull(defaultKeyGenerateAlgorithm);
assertTrue(defaultKeyGenerateAlgorithm instanceof IncrementKeyGenerateAlgorithm);
Object tableRules = FieldValueUtil.getFieldValue(shardingRule, "tableRules");
assertNotNull(tableRules);
assertThat(((Collection<TableRule>) tableRules).size(), is(2));
......@@ -82,6 +81,6 @@ public class GenerateKeyJUnitTest extends AbstractSpringJUnitTest {
TableRule orderItemRule = tableRuleIterator.next();
assertTrue(orderItemRule.getGenerateKeyColumn().isPresent());
assertThat(orderItemRule.getGenerateKeyColumn().get(), is("order_item_id"));
assertTrue(orderItemRule.getShardingKeyGenerator() instanceof DecrementKeyGenerator);
assertTrue(orderItemRule.getKeyGenerateAlgorithm() instanceof DecrementKeyGenerateAlgorithm);
}
}
......@@ -17,6 +17,11 @@
package org.apache.shardingsphere.shardingjdbc.spring;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.apache.shardingsphere.api.config.masterslave.LoadBalanceStrategyConfiguration;
import org.apache.shardingsphere.core.rule.MasterSlaveRule;
import org.apache.shardingsphere.core.strategy.masterslave.RandomMasterSlaveLoadBalanceAlgorithm;
......@@ -27,11 +32,6 @@ import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
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 {
......
......@@ -17,6 +17,18 @@
package org.apache.shardingsphere.shardingjdbc.spring;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.shardingsphere.api.config.sharding.strategy.ComplexShardingStrategyConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.HintShardingStrategyConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.InlineShardingStrategyConfiguration;
......@@ -38,29 +50,26 @@ import org.apache.shardingsphere.shardingjdbc.spring.algorithm.PreciseModuloData
import org.apache.shardingsphere.shardingjdbc.spring.algorithm.PreciseModuloTableShardingAlgorithm;
import org.apache.shardingsphere.shardingjdbc.spring.algorithm.RangeModuloTableShardingAlgorithm;
import org.apache.shardingsphere.shardingjdbc.spring.datasource.SpringShardingDataSource;
import org.apache.shardingsphere.shardingjdbc.spring.fixture.IncrementKeyGenerator;
import org.apache.shardingsphere.shardingjdbc.spring.fixture.IncrementKeyGenerateAlgorithm;
import org.apache.shardingsphere.shardingjdbc.spring.util.FieldValueUtil;
import org.apache.shardingsphere.underlying.common.config.properties.ConfigurationPropertyKey;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import org.apache.shardingsphere.underlying.common.config.properties.ConfigurationProperties;
import org.apache.shardingsphere.underlying.common.config.properties.ConfigurationPropertyKey;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.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/shardingNamespace.xml")
public class ShardingNamespaceTest extends AbstractJUnit4SpringContextTests {
@Test
public void assertKeyGenerator() {
assertThat(applicationContext.getBean("incrementAlgorithm"), instanceOf(KeyGenerateAlgorithm.class));
KeyGenerateAlgorithm incrementKeyGenerateAlgorithm = (KeyGenerateAlgorithm) applicationContext.getBean("incrementAlgorithm");
KeyGenerateAlgorithm directIncrementKeyGenerateAlgorithm = new IncrementKeyGenerateAlgorithm();
assertEquals(incrementKeyGenerateAlgorithm.generateKey(), directIncrementKeyGenerateAlgorithm.generateKey());
}
@Test
public void assertStandardStrategy() {
StandardShardingStrategyConfiguration standardStrategy = applicationContext.getBean("standardStrategy", StandardShardingStrategyConfiguration.class);
......@@ -126,7 +135,7 @@ public class ShardingNamespaceTest extends AbstractJUnit4SpringContextTests {
assertThat(shardingRule.getMasterSlaveRules().iterator().next().getLoadBalanceAlgorithm(), instanceOf(RoundRobinMasterSlaveLoadBalanceAlgorithm.class));
assertThat(shardingRule.getTableRules().size(), is(1));
assertThat(shardingRule.getTableRules().iterator().next().getLogicTable(), is("t_order"));
assertThat(shardingRule.getDefaultShardingKeyGenerator(), instanceOf(IncrementKeyGenerator.class));
assertThat(shardingRule.getDefaultKeyGenerateAlgorithm(), instanceOf(IncrementKeyGenerateAlgorithm.class));
}
@Test
......@@ -140,7 +149,7 @@ public class ShardingNamespaceTest extends AbstractJUnit4SpringContextTests {
assertThat(shardingRule.getMasterSlaveRules().iterator().next().getLoadBalanceAlgorithm(), instanceOf(RandomMasterSlaveLoadBalanceAlgorithm.class));
assertThat(shardingRule.getTableRules().size(), is(1));
assertThat(shardingRule.getTableRules().iterator().next().getLogicTable(), is("t_order"));
assertThat(shardingRule.getDefaultShardingKeyGenerator(), instanceOf(IncrementKeyGenerator.class));
assertThat(shardingRule.getDefaultKeyGenerateAlgorithm(), instanceOf(IncrementKeyGenerateAlgorithm.class));
}
@Test
......@@ -154,7 +163,7 @@ public class ShardingNamespaceTest extends AbstractJUnit4SpringContextTests {
new String[]{applicationContext.getBean("standardStrategy", StandardShardingStrategyConfiguration.class).getShardingColumn()}));
assertTrue(Arrays.equals(shardingRule.getDefaultTableShardingStrategy().getShardingColumns().toArray(new String[]{}),
new String[]{applicationContext.getBean("inlineStrategy", InlineShardingStrategyConfiguration.class).getShardingColumn()}));
assertThat(shardingRule.getDefaultShardingKeyGenerator(), instanceOf(IncrementKeyGenerator.class));
assertThat(shardingRule.getDefaultKeyGenerateAlgorithm(), instanceOf(IncrementKeyGenerateAlgorithm.class));
}
@Test
......@@ -178,7 +187,7 @@ public class ShardingNamespaceTest extends AbstractJUnit4SpringContextTests {
new String[]{applicationContext.getBean("inlineStrategy", InlineShardingStrategyConfiguration.class).getShardingColumn()}));
assertTrue(tableRule.getGenerateKeyColumn().isPresent());
assertThat(tableRule.getGenerateKeyColumn().get(), is("order_id"));
assertThat(tableRule.getShardingKeyGenerator(), instanceOf(IncrementKeyGenerator.class));
assertThat(tableRule.getKeyGenerateAlgorithm(), instanceOf(IncrementKeyGenerateAlgorithm.class));
}
@Test
......
......@@ -19,12 +19,12 @@ package org.apache.shardingsphere.shardingjdbc.spring.fixture;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
public final class DecrementKeyGenerator implements ShardingKeyGenerator {
public final class DecrementKeyGenerateAlgorithm implements KeyGenerateAlgorithm {
private final AtomicInteger sequence = new AtomicInteger(100);
......
......@@ -19,12 +19,12 @@ package org.apache.shardingsphere.shardingjdbc.spring.fixture;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import org.apache.shardingsphere.spi.keygen.KeyGenerateAlgorithm;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
public final class IncrementKeyGenerator implements ShardingKeyGenerator {
public final class IncrementKeyGenerateAlgorithm implements KeyGenerateAlgorithm {
private final AtomicInteger sequence = new AtomicInteger(100);
......
......@@ -37,6 +37,9 @@
<bean id="rangeModuloTableShardingAlgorithm" class="org.apache.shardingsphere.shardingjdbc.spring.algorithm.RangeModuloTableShardingAlgorithm" />
<bean id="defaultComplexKeysShardingAlgorithm" class="org.apache.shardingsphere.shardingjdbc.spring.algorithm.DefaultComplexKeysShardingAlgorithm" />
<bean id="defaultHintShardingAlgorithm" class="org.apache.shardingsphere.shardingjdbc.spring.algorithm.DefaultHintShardingAlgorithm" />
<bean id="incrementAlgorithm" class="org.apache.shardingsphere.shardingjdbc.spring.namespace.factorybean.KeyGenerateAlgorithmFactoryBean">
<property name="type" value="INCREMENT" />
</bean>
<sharding:standard-strategy id="standardStrategy" sharding-column="user_id" precise-algorithm-ref="preciseModuloDatabaseShardingAlgorithm" />
<sharding:standard-strategy id="rangeStandardStrategy" sharding-column="order_id" precise-algorithm-ref="preciseModuloTableShardingAlgorithm" range-algorithm-ref="rangeModuloTableShardingAlgorithm" />
......@@ -45,8 +48,8 @@
<sharding:hint-strategy id="hintStrategy" algorithm-ref="defaultHintShardingAlgorithm" />
<sharding:none-strategy id="noneStrategy" />
<sharding:key-generator id="defaultKeyGenerator" type="INCREMENT" column="id" />
<sharding:key-generator id="orderKeyGenerator" type="INCREMENT" column="order_id" />
<sharding:key-generator id="defaultKeyGenerator" column="id" algorithm-ref="incrementAlgorithm" />
<sharding:key-generator id="orderKeyGenerator" column="order_id" algorithm-ref="incrementAlgorithm" />
<master-slave:load-balance-algorithm id="randomLoadBalanceAlgorithm" type="RANDOM" />
<bean:properties id="props">
......
......@@ -28,13 +28,19 @@
<bean id="preciseModuloDatabaseShardingAlgorithm" class="org.apache.shardingsphere.shardingjdbc.spring.algorithm.PreciseModuloDatabaseShardingAlgorithm" />
<bean id="preciseModuloTableShardingAlgorithm" class="org.apache.shardingsphere.shardingjdbc.spring.algorithm.PreciseModuloTableShardingAlgorithm" />
<bean id="incrementAlgorithm" class="org.apache.shardingsphere.shardingjdbc.spring.namespace.factorybean.KeyGenerateAlgorithmFactoryBean">
<property name="type" value="INCREMENT" />
</bean>
<bean id="decrementAlgorithm" class="org.apache.shardingsphere.shardingjdbc.spring.namespace.factorybean.KeyGenerateAlgorithmFactoryBean">
<property name="type" value="DECREMENT" />
</bean>
<sharding:standard-strategy id="databaseStrategy" sharding-column="user_id" precise-algorithm-ref="preciseModuloDatabaseShardingAlgorithm" />
<sharding:standard-strategy id="tableStrategy" sharding-column="order_id" precise-algorithm-ref="preciseModuloTableShardingAlgorithm" />
<sharding:key-generator id="defaultKeyGenerator" type="INCREMENT" column="id" />
<sharding:key-generator id="itemKeyGenerator" type="DECREMENT" column="order_item_id" />
<sharding:key-generator id="orderKeyGenerator" type="INCREMENT" column="order_id" />
<sharding:key-generator id="defaultKeyGenerator" column="id" algorithm-ref="incrementAlgorithm" />
<sharding:key-generator id="itemKeyGenerator" column="order_item_id" algorithm-ref="decrementAlgorithm" />
<sharding:key-generator id="orderKeyGenerator" column="order_id" algorithm-ref="incrementAlgorithm" />
<sharding:data-source id="shardingDataSource">
<sharding:sharding-rule data-source-names="dbtbl_0,dbtbl_1" default-data-source-name="dbtbl_0" default-key-generator-ref="defaultKeyGenerator">
......
......@@ -15,5 +15,5 @@
# limitations under the License.
#
org.apache.shardingsphere.shardingjdbc.spring.fixture.DecrementKeyGenerator
org.apache.shardingsphere.shardingjdbc.spring.fixture.IncrementKeyGenerator
org.apache.shardingsphere.shardingjdbc.spring.fixture.DecrementKeyGenerateAlgorithm
org.apache.shardingsphere.shardingjdbc.spring.fixture.IncrementKeyGenerateAlgorithm
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册