import java.security.MessageDigest;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Encoder;
public class StringUtil {
/**
* 对字符串进行MD5哈希散列后编码为字符串返回
* @param str 原始字符串
* @return 新字符串
*/
public static String encodeMD5(String str) {
if (StringUtils.isEmpty(str)) {
throw new RuntimeException("can not encodeMD5 empty string");
}
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] md5Bytes = md5.digest(str.getBytes("utf-8"));
BASE64Encoder base64Encoder = new BASE64Encoder();
String encodeStr = base64Encoder.encode(md5Bytes);
return encodeStr;
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
*
* @param str
* @param baseModulo
* @return
*/
public static int hashAndModulo(String str, int baseModulo) {
if (StringUtils.isEmpty(str)) {
throw new RuntimeException("can not hashAndModulo empty string");
}
if (baseModulo <= 0) {
throw new RuntimeException("can not hashAndModulo when baseModulo<=0");
}
int hashCode = str.hashCode();
if (hashCode < 0) {
hashCode *= -1;
}
int mod = hashCode % baseModulo;
return mod;
}
public static void main(String[] args) {
// 验证能否把随机字符串打散后均匀分布到每个模中
Map<Integer, Integer> modMap = new TreeMap<Integer, Integer>();
int baseModulo = 10;// 对baseModulo取模
for (int i = 0; i < baseModulo; i++) {
modMap.put(i, 0);
}
int total = 1000000;// 样本数量
for (int i = 0; i < total; i++) {
String encodeMD5 = encodeMD5(UUID.randomUUID().toString());
int hashAndModulo = hashAndModulo("testStr_" + encodeMD5, baseModulo);
Integer integer = modMap.get(hashAndModulo);
modMap.put(hashAndModulo, 1 + integer);
}
Set<Entry<Integer, Integer>> entrySet = modMap.entrySet();
for (Entry<Integer, Integer> entry : entrySet) {
System.out.println(entry.getKey() + "-->" + 100 * ((double) (entry.getValue())) / total + "%");
}
}
}
大样本下得到的测试结果:
0-->9.9504%
1-->9.9833%
2-->9.9965%
3-->9.9593%
4-->10.0141%
5-->10.0054%
6-->10.0816%
7-->10.007%
8-->10.0161%
9-->9.9863%