Skip to content

Commit

Permalink
apache#1751 fix bug and add a unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
rushsky518 committed Feb 3, 2020
1 parent ce0c14c commit 4fb7710
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 14 deletions.
Expand Up @@ -39,11 +39,8 @@ public class MessageClientIDSetter {
}
LEN = ip.length + 4 + 4 + 4 + 2;
ByteBuffer tempBuffer = ByteBuffer.allocate(ip.length + 4 + 4);
tempBuffer.position(0);
tempBuffer.put(ip);
tempBuffer.position(ip.length);
tempBuffer.putInt(UtilAll.getPid());
tempBuffer.position(ip.length + 4);
tempBuffer.putInt(MessageClientIDSetter.class.getClassLoader().hashCode());
FIX_STRING = UtilAll.bytes2string(tempBuffer.array());
setStartTime(System.currentTimeMillis());
Expand Down Expand Up @@ -107,6 +104,15 @@ public static byte[] getIPFromID(String msgID) {
return result;
}

public static int getPidFromID(String msgID) {
byte[] bytes = UtilAll.string2bytes(msgID);
int ipLength = bytes.length == 30 ? 16 : 4;
ByteBuffer wrap = ByteBuffer.wrap(bytes);
wrap.position(ipLength);
int pid = wrap.getInt();
return pid;
}

public static String createUniqID() {
StringBuilder sb = new StringBuilder(LEN * 2);
sb.append(FIX_STRING);
Expand All @@ -120,7 +126,6 @@ private static byte[] createUniqIDBuffer() {
if (current >= nextStartTime) {
setStartTime(current);
}
buffer.position(0);
buffer.putInt((int) (System.currentTimeMillis() - startTime));
buffer.putShort((short) COUNTER.getAndIncrement());
return buffer.array();
Expand Down
Expand Up @@ -17,26 +17,32 @@

package org.apache.rocketmq.common.message;

import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.UtilAll;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class MessageClientIDSetterTest {

@Test
public void testCreateUniqID() {
public void testGetIPStrFromID() {
byte[] ip = UtilAll.getIP();
String ipStr = (4 == ip.length) ? UtilAll.ipToIPv4Str(ip) : UtilAll.ipToIPv6Str(ip);

String uniqID = MessageClientIDSetter.createUniqID();
System.out.println(uniqID);
String ipStrFromID = MessageClientIDSetter.getIPStrFromID(uniqID);

assertThat(ipStr).isEqualTo(ipStrFromID);
}

@Test
public void testGetIPStrFromID() {
String ipv4HostMsgId = "C0A803CA00002A9F0000000000031367";
String ipv6HostMsgId = "24084004018081003FAA1DDE2B3F898A00002A9F0000000000000CA0";
String v4Ip = "192.168.3.202";
String v6Ip = "2408:4004:0180:8100:3faa:1dde:2b3f:898a";
assertThat(MessageClientIDSetter.getIPStrFromID(ipv4HostMsgId)).isEqualTo(v4Ip);
assertThat(MessageClientIDSetter.getIPStrFromID(ipv6HostMsgId)).isEqualTo(v6Ip);
}
public void testGetPidFromID() {
long pid = MixAll.getPID();

String uniqID = MessageClientIDSetter.createUniqID();
int pidFromID = MessageClientIDSetter.getPidFromID(uniqID);

assertThat(pid).isEqualTo(pidFromID);
}
}

0 comments on commit 4fb7710

Please sign in to comment.