memcache的分布式hash算法
/**
* Internal private hashing method.
*
* This is the original hashing algorithm from other clients.
* Found to be slow and have poor distribution.
*
* @param key String to hash
* @return hashCode for this string using our own hashing algorithm
*/
private static long origCompatHashingAlg( String key ) {
long hash = 0;
char[] cArr = key.toCharArray();
for ( int i = 0; i < cArr.length; ++i ) {
hash = (hash * 33) + cArr;
}
return hash;
}
/**
* Internal private hashing method.
*
* This is the new hashing algorithm from other clients.
* Found to be fast and have very good distribution.
*
* UPDATE: This is dog slow under java
*
* @param key
* @return
*/
private static long newCompatHashingAlg( String key ) {
CRC32 checksum = new CRC32();
checksum.update( key.getBytes() );
long crc = checksum.getValue();
return (crc >> 16) & 0x7fff;
}
/**
* Internal private hashing method.
*
* MD5 based hash algorithm for use in the consistent
* hashing approach.
*
* @param key
* @return
*/
private static long md5HashingAlg( String key ) {
MessageDigest md5 = MD5.get();
md5.reset();
md5.update( key.getBytes() );
byte[] bKey = md5.digest();
long res = ((long)(bKey&0xFF) << 24) | ((long)(bKey&0xFF) << 16) | ((long)(bKey&0xFF) << 8) | (long)(bKey&0xFF);
return res;
}
/**
* Returns a bucket to check for a given key.
*
* @param key String key cache is stored under
* @return int bucket
*/
private long getHash( String key, Integer hashCode ) {
if ( hashCode != null ) {
if ( hashingAlg == CONSISTENT_HASH )
return hashCode.longValue() & 0xffffffffL;
else
return hashCode.longValue();
}
else {
switch ( hashingAlg ) {
case NATIVE_HASH:
return (long)key.hashCode();
case OLD_COMPAT_HASH:
return origCompatHashingAlg( key );
case NEW_COMPAT_HASH:
return newCompatHashingAlg( key );
case CONSISTENT_HASH:
return md5HashingAlg( key );
default:
// use the native hash as a default
hashingAlg = NATIVE_HASH;
return (long)key.hashCode();
}
}
}
默认是NATIVE_HASH这种。
页:
[1]