算法介绍
MurmurHash 是一种非加密型哈希函数,适用于一般的哈希检索操作。已经被应用到很多开源项目如Redis,Memcached,Cassandra,HBase,Lucene等。与其它流行的哈希函数相比,对于规律性较强的key,MurmurHash的随机分布特征表现更良好。
MurmurHash is a non-cryptographic hash function suitable for general hash-based lookup.The name comes from two basic operations, multiply (MU) and rotate (R), used in its inner loop. Unlike cryptographic hash functions, it is not specifically designed to be difficult to reverse by an adversary, making it unsuitable for cryptographic purposes.
优缺点
- 速度快,比安全散列算法快几十倍;
- 变化足够激烈,相似的字符串如“abc”和“abd”能够均匀散落在哈希环上;
- 不保证安全性(缺点);
算法实现
Guava的Hashing类,Jedis和Cassandra的Util类均提供了MurmurHash算法的Java实现,Guava使用示例如下所示:
import java.nio.charset.Charset;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
/**
* 类说明:MurmurHash算法测试类
*
* @author ruipeng.lrp
* @since 2018/3/11
*/
public class Murmur3_32HashFunctionTest {
public static void main(String[] args) {
HashFunction function = Hashing.murmur3_32();
HashCode hascode = function.hashString("hello1", Charset.forName("utf-8"));
System.out.println(hascode.asInt());
HashCode hascode2 = function.hashString("hello2", Charset.forName("utf-8"));
System.out.println(hascode2.asInt());
HashCode hascode3 = function.hashString("hello3", Charset.forName("utf-8"));
System.out.println(hascode3.asInt());
}
}
参考: