Skip to content

Commit

Permalink
fixed #192 Extract workerId from hostname string
Browse files Browse the repository at this point in the history
  • Loading branch information
hanahmily authored and gaohongtao committed Dec 11, 2016
1 parent 1ad2ad8 commit b825236
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 38 deletions.
Original file line number Diff line number Diff line change
@@ -1,51 +1,61 @@
/*
* 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 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。
* 根据机器名最后的数字编号获取工作进程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;
private final CommonSelfIdGenerator commonSelfIdGenerator = new CommonSelfIdGenerator();

static {
COMMON_SELF_ID_GENERATOR = new CommonSelfIdGenerator();
initWorkerId();
}

static void initWorkerId() {
InetAddress addr;
InetAddress address;
Long workerId;
try {
addr = InetAddress.getLocalHost();
address = InetAddress.getLocalHost();
} catch (final UnknownHostException e) {
throw new IllegalStateException("Cannot get LocalHost InetAddress , please check your network!");
throw new IllegalStateException("Cannot get LocalHost InetAddress, please check your network!");
}
String hostName = address.getHostName();
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!");
throw new IllegalArgumentException(String.format("Wrong hostname:%s, hostname must be end with number!", hostName));
}
CommonSelfIdGenerator.setWorkerId(workerId);
}

@Override
public Number generateId() {
return COMMON_SELF_ID_GENERATOR.generateId();
return commonSelfIdGenerator.generateId();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

package com.dangdang.ddframe.rdb.sharding.id.generator.self;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
Expand All @@ -40,37 +40,38 @@
import static org.junit.Assert.assertThat;

@RunWith(PowerMockRunner.class)
@PrepareForTest({HostNameIdGenerator.class})
@PrepareForTest(HostNameIdGenerator.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class HostNameIdGeneratorTest {

private static InetAddress rightAddress;

private static InetAddress wrongAddress;

@Rule
public ExpectedException exception = ExpectedException.none();

private InetAddress rightAddr;

private InetAddress wrongAddr;

@Before
public void init() throws UnknownHostException {
int ipv4Int = -1062731412;

@BeforeClass
public static void init() throws UnknownHostException {
String ipv4 = "192.168.1.108";
byte[] ipv4Byte = new byte[4];
String[] ipv4StingArray = ipv4.split("\\.");
for (int i = 0; i < 4; i++) {
ipv4Byte[i] = (byte) (ipv4Int >>> (24 - i * 8));
ipv4Byte[i] = (byte) Integer.valueOf(ipv4StingArray[i]).intValue();
}
rightAddr = InetAddress.getByAddress("dangdang-db-sharding-dev-233", ipv4Byte);
wrongAddr = InetAddress.getByAddress("dangdang-db-sharding-dev", ipv4Byte);
rightAddress = InetAddress.getByAddress("dangdang-db-sharding-dev-233", ipv4Byte);
wrongAddress = InetAddress.getByAddress("dangdang-db-sharding-dev", ipv4Byte);
//static init HostNameIdGenerator
PowerMockito.mockStatic(InetAddress.class);
PowerMockito.when(InetAddress.getLocalHost()).thenReturn(rightAddr);
new HostNameIdGenerator();
PowerMockito.when(InetAddress.getLocalHost()).thenReturn(rightAddress);
HostNameIdGenerator.initWorkerId();
}

@Test
public void testRightHostName() throws UnknownHostException {
PowerMockito.mockStatic(InetAddress.class);
PowerMockito.when(InetAddress.getLocalHost()).thenReturn(rightAddr);
PowerMockito.when(InetAddress.getLocalHost()).thenReturn(rightAddress);
HostNameIdGenerator.initWorkerId();
HostNameIdGenerator idGenerator = new HostNameIdGenerator();
assertThat(CommonSelfIdGenerator.getWorkerId(), is(233L));
}

Expand All @@ -79,23 +80,23 @@ 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!");
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);
PowerMockito.when(InetAddress.getLocalHost()).thenReturn(wrongAddress);
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Wrong hostname , hostname must be end with number!");
exception.expectMessage(String.format("Wrong hostname:%s, hostname must be end with number!", wrongAddress.getHostName()));
HostNameIdGenerator.initWorkerId();
}

@Test
public void generateId() throws Exception {
PowerMockito.mockStatic(InetAddress.class);
PowerMockito.when(InetAddress.getLocalHost()).thenReturn(rightAddr);
PowerMockito.when(InetAddress.getLocalHost()).thenReturn(rightAddress);
HostNameIdGenerator.initWorkerId();
int threadNumber = Runtime.getRuntime().availableProcessors() << 1;
ExecutorService executor = Executors.newFixedThreadPool(threadNumber);
Expand Down

0 comments on commit b825236

Please sign in to comment.