tags:

views:

54

answers:

2

I use Php memcache on PHP Version 5.2.4-2ubuntu5.10 Below you can find the info from phpinfo.

When I use key larger than 250 characters memcache returns true on $memcache->set and false on $memcache->get .

Any idea how to set it to work normally (truncate key at 250 chars)?

If not - what would be the easiest way to override memcache across all my code to log the calls and know where I should change the key? Thanks

memcache support    enabled
Active persistent connections   0
Revision    $Revision: 1.86 $

Directive   Local Value Master Value
memcache.allow_failover 1   1
memcache.chunk_size 8192    8192
memcache.default_port   11211   11211
memcache.hash_function  crc32   crc32
memcache.hash_strategy  standard    standard
memcache.max_failover_attempts  20  20
+1  A: 

Take your long key and run it through md5() when you get or set it. That way your key is always 32 characters long and you shouldn't have to worry about it.

Something like:

$memcache->set(md5('really long key'), $value);

Then to get:

$memcache->get(md5('really long key'));
Cfreak
or use `sha1($value)`, which is always 40 characters long and has less chance of collision because of it.
R. Bemrose
Best yet, since this is newer than PHP 5.1.2, `hash('sha256', $value)`
R. Bemrose
Thanks , I'm aware of this, but I'm interested in either - setting memcache to work with longer keys (by ignoring the rest of the key) or checking whether this issue has implication somewhere in my code in the most efficient way, so I'll be able to add hashing where it is needed
Nir
+2  A: 

The maximum size is indeed 250 (see here).

You shouldn't truncate the keys, as it can map keys that were different to the same value (same for md5, though it's highly unlikely to happen by accident).

If you want to detect the cases where it's happening and since you're using the OOP interface, you can decorate the memcache object, overriding set or get (or both) to throw an exception or an error when it finds a long key.

With only inheritance (no decoration), you can do

class MemcacheEx extends Memcache {
    public function set($key, $var, int $flag=0, $expire=0) {
        //do something with $key
        parent::set($key, $var, $flag, $expire);
    }

    //... similar for get
}
$memcache = new MemcacheEx(); //instead of new Memcache()
//...
Artefacto
Truncating to 250 should be OK since I knew the key would be truncated to 250 when I wrote the code. Any idea how to decorate the memcache object? I have little experience with overriding methods in PHP.
Nir