提交 ab78772d 编写于 作者: G gaohongtao

fixed #191 Using IP lowest bit to generate worker id

上级 3eed43bf
......@@ -8,6 +8,11 @@ weight = 1
## 1.4.1-SNAPSHOT
### 功能提升
1. [ISSUE #191](https://github.com/dangdangdotcom/sharding-jdbc/issues/191) 根据主机的IP生成workerId的IdGenerator实现
1. [ISSUE #192](https://github.com/dangdangdotcom/sharding-jdbc/issues/192) 根据HOSTNAME的数字尾缀获取workerId的IdGenerator
### 缺陷修正
1. [ISSUE #194](https://github.com/dangdangdotcom/sharding-jdbc/issues/194) jdbc接口中资源释放错误
......
......@@ -112,6 +112,15 @@ public class CommonSelfIdGenerator implements IdGenerator {
CommonSelfIdGenerator.workerId = workerId;
}
/**
* 获取工作Id的二进制长度.
*
* @return 工作Id的二进制长度
*/
public static long getWorkerIdLength() {
return WORKER_ID_BITS;
}
/**
* 生成Id.
*
......
......@@ -23,9 +23,9 @@ import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* 根据机器IP获取工作进程Id,如果线上机器的IP二进制表示的最后10位不重复,建议使用此种方式
* ,列如机器的IP为192.168.1.108,二进制表示:11000000 10101000 00000001 01101100
* ,截取最后10位 01 01101100,转为十进制364,设置workerId为364
* 根据机器IP获取工作进程Id,如果线上机器的IP二进制表示的最后10位不重复,建议使用此种方式
* ,列如机器的IP为192.168.1.108,二进制表示:11000000 10101000 00000001 01101100
* ,截取最后10位 01 01101100,转为十进制364,设置workerId为364.
*
* @author DonneyYoung
*/
......@@ -39,15 +39,13 @@ public class IPIdGenerator implements IdGenerator {
static void initWorkerId() {
InetAddress address;
Long workerId;
try {
address = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
} catch (final UnknownHostException e) {
throw new IllegalStateException("Cannot get LocalHost InetAddress, please check your network!");
}
String[] ipAddress = address.getHostAddress().split("\\.");
workerId = ((Long.valueOf(ipAddress[ipAddress.length - 2]) & 0b11) << 8) + Long.valueOf(ipAddress[ipAddress.length - 1]);
CommonSelfIdGenerator.setWorkerId(workerId);
byte[] ipAddressByteArray = address.getAddress();
CommonSelfIdGenerator.setWorkerId((long) (((ipAddressByteArray[ipAddressByteArray.length - 2] & 0B11) << Byte.SIZE) + (ipAddressByteArray[ipAddressByteArray.length - 1] & 0xFF)));
}
@Override
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册