开发者

Can memcached keys contain spaces?

开发者 https://www.devze.com 2023-03-01 16:19 出处:网络
I seem to have problems with memcached开发者_开发技巧 keys that have spaces, though I can\'t pinpoint exactly what.A more explicit answer (referred to by Dustin, but not referenced):

I seem to have problems with memcached开发者_开发技巧 keys that have spaces, though I can't pinpoint exactly what.


A more explicit answer (referred to by Dustin, but not referenced):

Keys

Data stored by memcached is identified with the help of a key. A key is a text string which should uniquely identify the data for clients that are interested in storing and retrieving it. Currently the length limit of a key is set at 250 characters (of course, normally clients wouldn't need to use such long keys); the key must not include control characters or whitespace.

Source: protocol.txt (Specific Version)


No. Memcached keys cannot contain spaces.


Memcached clients seem not to validate keys in favor of performance.

What I usually do is create a method named createWellFormedKey($key) and pass the returned result to the set() and get() methods of the memcached client.

I do not use md5 and sha1 hashing unless the base64 version exceeds 250 characters. This is because md5 and sha1 are more expensive operations performance wise.

A sample PHP code looks like this:

/**
 * Generates a well formed key using the following algorithm:
 * 1. base64_encode the key first to make sure all characters are valid
 * 2. Check length of result, less than 250 then return it
 * 3. Length of result more than 250 then create a key that is md5($validKey).sha1($validKey).strlen($validKey)
 */
private function createWellFormedKey($key) {
    // Get rid of all spaces, control characters, etc using base64
    $validKey = base64_encode($key);

    $validKeyLength = strlen($validKey);
    // 250 is the maximum memcached can handle
    if (strlen($validKey) < 250) {
        return $validKey;
    }

    $validKey = md5($validKey).sha1($validKey).$validKeyLength;
    return $validKey;
}


At the moment I'm playing around with memcached with PHP and the Problem described IMHO can be easily solved by using hash algorithms like md5 and sha1 (or any other).

I'm using a combination of a md5-hash, sha1-hash and sha256 + the length of the key given. Obviously this method can be reduced to two hash-methods + length of the key, so you can easily avoid using space or other characters that should not be in the key.

In my opinion the hash-collions are avoided because the chance that both hash algorithms have a collision is nearly 0. By additionally using the key length in the key the problem of a collision is 0.


Applications using the memcached binary protocol can use whitespace-containing keys, though there is still a 250-byte length limit.

0

精彩评论

暂无评论...
验证码 换一张
取 消