Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memcached client throws java.lang.IllegalArgumentException: Key contains invalid characters

Seems memcache client doesn't support UTF-8 string as its key. But I have to use i18n. Anyway to fix it?

java.lang.IllegalArgumentException: Key contains invalid characters: ``HK:00:A Kung Wan'' at net.spy.memcached.MemcachedClient.validateKey(MemcachedClient.java:232) at net.spy.memcached.MemcachedClient.addOp(MemcachedClient.java:254)

like image 445
user398384 Avatar asked Dec 12 '22 10:12

user398384


2 Answers

The issue here isn't UTF encoding. It's the fact that your key contains a space. Keys cannot have spaces, new lines, carriage returns, or null characters.

The line of code that produces the exception is below

if (b == ' ' || b == '\n' || b == '\r' || b == 0) {
    throw new IllegalArgumentException
        ("Key contains invalid characters:  ``" + key + "''");
}
like image 176
mikewied Avatar answered May 30 '23 01:05

mikewied


Base64 Encode your key just before passing them to memcached client's set() and get() methods.

A general solution to handle all memcached keys with special characters, control characters, new lines, spaces, unicode characters, etc. is to base64 encode the key just before you pass it to the set() and get() methods of memcached.

// pseudo code for set
memcachedClient.set(Base64.encode(key), value);

// pseudo code for get
memcachedClient.get(Base64.encode(key));

This converts them into characters memcached is guaranteed to understand. In addition, base64 encoding has no performance penalty (unless you are a nano performance optimization guy), base64 is reliable and takes only about 30% extra length.

Works like a charm!

like image 30
Basil Musa Avatar answered May 30 '23 01:05

Basil Musa