Skip to content

Commit f6bd816

Browse files
author
gaohongtao
committed
fixed #191 Using IP lowest bit to generate worker id
1 parent 94b0b3d commit f6bd816

File tree

3 files changed

+20
-8
lines changed

3 files changed

+20
-8
lines changed

sharding-jdbc-doc/content/post/release_notes.md

+5
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@ weight = 1
88

99
## 1.4.1-SNAPSHOT
1010

11+
### 功能提升
12+
13+
1. [ISSUE #191](https://github.com/dangdangdotcom/sharding-jdbc/issues/191) 根据主机的IP生成workerId的IdGenerator实现
14+
1. [ISSUE #192](https://github.com/dangdangdotcom/sharding-jdbc/issues/192) 根据HOSTNAME的数字尾缀获取workerId的IdGenerator
15+
1116
### 缺陷修正
1217

1318
1. [ISSUE #194](https://github.com/dangdangdotcom/sharding-jdbc/issues/194) jdbc接口中资源释放错误

sharding-jdbc-id-generator-parent/sharding-jdbc-self-id-generator/src/main/java/com/dangdang/ddframe/rdb/sharding/id/generator/self/CommonSelfIdGenerator.java

+9
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,15 @@ public static void setWorkerId(final Long workerId) {
112112
CommonSelfIdGenerator.workerId = workerId;
113113
}
114114

115+
/**
116+
* 获取工作Id的二进制长度.
117+
*
118+
* @return 工作Id的二进制长度
119+
*/
120+
public static long getWorkerIdLength() {
121+
return WORKER_ID_BITS;
122+
}
123+
115124
/**
116125
* 生成Id.
117126
*

sharding-jdbc-id-generator-parent/sharding-jdbc-self-id-generator/src/main/java/com/dangdang/ddframe/rdb/sharding/id/generator/self/IPIdGenerator.java

+6-8
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,9 @@
2323
import java.net.UnknownHostException;
2424

2525
/**
26-
* 根据机器IP获取工作进程Id如果线上机器的IP二进制表示的最后10位不重复建议使用此种方式
27-
* 列如机器的IP为192.168.1.108二进制表示11000000 10101000 00000001 01101100
28-
* 截取最后10位 01 01101100转为十进制364设置workerId为364
26+
* 根据机器IP获取工作进程Id,如果线上机器的IP二进制表示的最后10位不重复,建议使用此种方式
27+
* ,列如机器的IP为192.168.1.108,二进制表示:11000000 10101000 00000001 01101100
28+
* ,截取最后10位 01 01101100,转为十进制364,设置workerId为364.
2929
*
3030
* @author DonneyYoung
3131
*/
@@ -39,15 +39,13 @@ public class IPIdGenerator implements IdGenerator {
3939

4040
static void initWorkerId() {
4141
InetAddress address;
42-
Long workerId;
4342
try {
4443
address = InetAddress.getLocalHost();
45-
} catch (UnknownHostException e) {
44+
} catch (final UnknownHostException e) {
4645
throw new IllegalStateException("Cannot get LocalHost InetAddress, please check your network!");
4746
}
48-
String[] ipAddress = address.getHostAddress().split("\\.");
49-
workerId = ((Long.valueOf(ipAddress[ipAddress.length - 2]) & 0b11) << 8) + Long.valueOf(ipAddress[ipAddress.length - 1]);
50-
CommonSelfIdGenerator.setWorkerId(workerId);
47+
byte[] ipAddressByteArray = address.getAddress();
48+
CommonSelfIdGenerator.setWorkerId((long) (((ipAddressByteArray[ipAddressByteArray.length - 2] & 0B11) << Byte.SIZE) + (ipAddressByteArray[ipAddressByteArray.length - 1] & 0xFF)));
5149
}
5250

5351
@Override

0 commit comments

Comments
 (0)