Memcache key generation strategy

Posted by Maxim Veksler on Stack Overflow See other posts from Stack Overflow or by Maxim Veksler
Published on 2010-04-15T09:40:59Z Indexed on 2010/04/15 9:43 UTC
Read the original article Hit count: 397

Given function f1 which receives n String arguments, would be considered better random key generation strategy for memcache for the scenario described below ?

Our Memcache client does internal md5sum hashing on the keys it gets

   public class MemcacheClient {  
       public Object get(String key) {
            String md5 = Md5sum.md5(key)
            // Talk to memcached to get the Serialization... 
            return memcached(md5);
       }
   }

First option

    public static String f1(String s1, String s2, String s3, String s4) {
         String key = s1 +  s2 + s3 + s4;
         return get(key);
    }

Second option

    /**
     * Calculate hash from Strings
     *
     * @param objects vararg list of String's
     *
     * @return calculated md5sum hash
     */
    public static String stringHash(Object... strings) {
        if(strings == null) 
            throw new NullPointerException("D'oh! Can't calculate hash for null");

        MD5 md5sum = new MD5();

//      if(prevHash != null)
//          md5sum.Update(prevHash);

        for(int i = 0; i < strings.length; i++) {
            if(strings[i] != null) {
                md5sum.Update("_" + strings[i] + "_"); // Convert to String...
            } else {
                // If object is null, allow minimum entropy  by hashing it's position
                md5sum.Update("_" + i + "_");
            }
        }

        return md5sum.asHex();
    }


    public static String f1(String s1, String s2, String s3, String s4) {
         String key = stringHash(s1, s2, s3, s4);
         return get(key);
    }

Note that the possible problem with the second option is that we are doing second md5sum (in the memcache client) on an already md5sum'ed digest result.

Thanks for reading, Maxim.

© Stack Overflow or respective owner

Related posts about memcache

Related posts about md5