提交 1ad2ad8c 编写于 作者: D DonneyYoung

add HostNameIdGenerator.

上级 de6bf4f6
......@@ -71,6 +71,7 @@
<taglist-maven-plugin.version>2.4</taglist-maven-plugin.version>
<maven-gpg-plugin.version>1.6</maven-gpg-plugin.version>
<javadocExecutable>${java.home}/../bin/javadoc</javadocExecutable>
<powermock.version>1.6.6</powermock.version>
</properties>
<dependencyManagement>
......@@ -268,6 +269,24 @@
<artifactId>elastic-job-core</artifactId>
<version>${elastic-job.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
......
......@@ -30,5 +30,20 @@
<artifactId>jcl-over-slf4j</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.dangdang.ddframe.rdb.sharding.id.generator.self;
import com.dangdang.ddframe.rdb.sharding.id.generator.IdGenerator;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* .
* 根据机器名最后的数字编号获取工作进程Id,如果线上机器命名有统一规范,建议使用此种方式
* ,列如机器的HostName为
* ,dangdang-db-sharding-dev-01(公司名-部门名-服务名-环境名-编号)
* ,会截取HostName最后的编号01作为workerId。
*
* @author DonneyYoung
**/
@Getter
@Slf4j
public class HostNameIdGenerator implements IdGenerator {
private static final CommonSelfIdGenerator COMMON_SELF_ID_GENERATOR;
static {
COMMON_SELF_ID_GENERATOR = new CommonSelfIdGenerator();
initWorkerId();
}
static void initWorkerId() {
InetAddress addr;
Long workerId;
try {
addr = InetAddress.getLocalHost();
} catch (final UnknownHostException e) {
throw new IllegalStateException("Cannot get LocalHost InetAddress , please check your network!");
}
try {
String hostName = addr.getHostName();
workerId = Long.valueOf(hostName.replace(hostName.replaceAll("\\d+$", ""), ""));
} catch (final NumberFormatException e) {
throw new IllegalArgumentException("Wrong hostname , hostname must be end with number!");
}
CommonSelfIdGenerator.setWorkerId(workerId);
}
@Override
public Number generateId() {
return COMMON_SELF_ID_GENERATOR.generateId();
}
}
......@@ -25,7 +25,8 @@ import org.junit.runners.Suite;
ApiWorkerIdTest.class,
SystemPropertyWorkerIdTest.class,
SystemEnvWorkerIdTest.class,
CommonSelfIdGeneratorTest.class
CommonSelfIdGeneratorTest.class,
HostNameIdGeneratorTest.class
})
public class AllTest {
}
/*
* 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 com.dangdang.ddframe.rdb.sharding.id.generator.self;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
@RunWith(PowerMockRunner.class)
@PrepareForTest({HostNameIdGenerator.class})
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class HostNameIdGeneratorTest {
@Rule
public ExpectedException exception = ExpectedException.none();
private InetAddress rightAddr;
private InetAddress wrongAddr;
@Before
public void init() throws UnknownHostException {
int ipv4Int = -1062731412;
byte[] ipv4Byte = new byte[4];
for (int i = 0; i < 4; i++) {
ipv4Byte[i] = (byte) (ipv4Int >>> (24 - i * 8));
}
rightAddr = InetAddress.getByAddress("dangdang-db-sharding-dev-233", ipv4Byte);
wrongAddr = InetAddress.getByAddress("dangdang-db-sharding-dev", ipv4Byte);
PowerMockito.mockStatic(InetAddress.class);
PowerMockito.when(InetAddress.getLocalHost()).thenReturn(rightAddr);
new HostNameIdGenerator();
}
@Test
public void testRightHostName() throws UnknownHostException {
PowerMockito.mockStatic(InetAddress.class);
PowerMockito.when(InetAddress.getLocalHost()).thenReturn(rightAddr);
HostNameIdGenerator.initWorkerId();
HostNameIdGenerator idGenerator = new HostNameIdGenerator();
assertThat(CommonSelfIdGenerator.getWorkerId(), is(233L));
}
@Test
public void testUnknownHost() throws UnknownHostException {
PowerMockito.mockStatic(InetAddress.class);
PowerMockito.when(InetAddress.getLocalHost()).thenThrow(new UnknownHostException());
exception.expect(IllegalStateException.class);
exception.expectMessage("Cannot get LocalHost InetAddress , please check your network!");
HostNameIdGenerator.initWorkerId();
}
@Test
public void testWrongHostName() throws UnknownHostException {
PowerMockito.mockStatic(InetAddress.class);
PowerMockito.when(InetAddress.getLocalHost()).thenReturn(wrongAddr);
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Wrong hostname , hostname must be end with number!");
HostNameIdGenerator.initWorkerId();
}
@Test
public void generateId() throws Exception {
PowerMockito.mockStatic(InetAddress.class);
PowerMockito.when(InetAddress.getLocalHost()).thenReturn(rightAddr);
HostNameIdGenerator.initWorkerId();
int threadNumber = Runtime.getRuntime().availableProcessors() << 1;
ExecutorService executor = Executors.newFixedThreadPool(threadNumber);
final int taskNumber = threadNumber << 2;
final HostNameIdGenerator idGenerator = new HostNameIdGenerator();
Set<Long> hashSet = new HashSet<>();
for (int i = 0; i < taskNumber; i++) {
hashSet.add(executor.submit(new Callable<Long>() {
@Override
public Long call() throws Exception {
return (Long) idGenerator.generateId();
}
}).get());
}
assertThat(hashSet.size(), is(taskNumber));
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册