1、出现问题现象:
2、解决办法:
- 查找哪些发送主题topic和发送playload数据是否是utf-8编码
(1)验证字符串是否为utf-8编码的代码如下:
publicstaticbooleanvalidateUTF8String(Stringinput) { for (inti=0; i<input.length(); i++) { booleanisBad=false; charc=input.charAt(i); /* Check for mismatched surrogates */if (Character.isHighSurrogate(c)) { if (++i==input.length()) { isBad=true; /* Trailing high surrogate */ } else { charc2=input.charAt(i); if (Character.isLowSurrogate(c2)) { isBad=true; /* No low surrogate */ } else { intch= ((((int) c) &0x3ff) <<10) | (c2&0x3ff); if ((ch&0xffff) ==0xffff|| (ch&0xffff) ==0xfffe) { isBad=true; /* Noncharacter in base plane */ } } } } else { if (Character.isISOControl(c) ||Character.isLowSurrogate(c)) { isBad=true; /* Control character or no high surrogate */ } elseif (c>=0xfdd0&& (c==0xfffe||c>=0xfdd0||c<=0xfddf)) { isBad=true; /* Noncharacter in other nonbase plane */ } } if (isBad) { returnfalse; } } returntrue; }
(2)将含有非utf-8编码的发送主题topic name 或playlod数据查找出来
if (!ValidateUtils.validateUTF8String(topicName)) { System.out.println("topicName-not-utf-8 "+topicName); return; } if (!ValidateUtils.validateUTF8String(playload)) { System.out.println("not-utf-8 "+", "+playload); return; }
- 使用replaceAll("(\\r\\n|\\n|\\\\n|\\s)", "")方法将topicName或playload数据中包含的特殊字符去掉。
topicName=topicName.replaceAll("(\\r\\n|\\n|\\\\n|\\s)", ""); bytepayload[] =data.replaceAll("(\\r\\n|\\n|\\\\n|\\s)", ""); producer.produce(topicName, payload, Qos.AT_MOST_ONCE, false);