Using 'incr' with spymemcached client
Asked Answered
M

2

7

I am trying set up a very basic hit rate monitor in memcached using the spymemcached-2.8.4 client however the value stored in memcached never actually seems to increment... Is this a bug or am I missing something?

public static void checkHitRate(String clientId) throws FatalException, ForbiddenException {
    MemcachedClient memcachedClient;
    try {
        memcachedClient = new MemcachedClient(new InetSocketAddress("localhost", 11211));

        Integer hitRate = (Integer) memcachedClient.get(clientId);

        if (hitRate == null) {
            memcachedClient.set(clientId, 1800, 1);
        } else if (hitRate > 500) {
            throw new ForbiddenException("Hit rate too high. Try again later");
        } else if (hitRate <= 500) { 
            memcachedClient.incr(clientId, 1);
        } 

    } catch (IOException e) {
        throw new FatalException("Could not read hit rate from Memcached.");
    }
}

I know its possible in memcached:

(TELENT output)

set clientId_1 0 200 1
1
STORED
incr clientId_1 1
2
get clientId_1
VALUE clientId_1 0 1
2
END
Maggs answered 25/10, 2012 at 21:9 Comment(4)
Have you tried using telnet to connect to memcached server and perform this operations manually? does it work? see on memcached commands: javaworld.com/javaworld/jw-04-2012/…Siple
Yep it's defo possible (see edits)...Maggs
try enabling verbose mode for the memcached server (e.g. in comman-line run memcached -vv) to see errors on the server during incr operation (it complains "CLIENT_ERROR cannot increment or decrement non-numeric value") also in your Java app you should get exception...Siple
I would recommend checking to see what the set and incr functions in you java code return. This way you can see if an operation failed for some reason.Curable
G
8

For incr/decr memcached server considers stored values as string representation of integer,

Adding an item like

    memcachedClient.set(clientId, 1800, 1);

adds value as an integer that's why memcached is unable to increment it.

Use

    memcachedClient.set(clientId, 1800, "1");

instead. It will work as you need.

Grubstake answered 31/10, 2013 at 10:33 Comment(0)
S
2

You can use another incr signature:

System.out.println("Incr result: " + memcachedClient.incr("testIncrKey", 1, 1));

That works for me with spymemcached-2.8.4 client.

Also, looks like there was an issue with incr spymemcached.

You should not use Integer since it will be converted back to String and stored as String on memcached server.

If you open using xmemcached then you can use specific Counter construct, e.g.

Counter counter=client.getCounter("counter",0);
counter.incrementAndGet();
counter.decrementAndGet();
counter.addAndGet(-10);

read more on it in xmemcached documentation:

Siple answered 26/10, 2012 at 17:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.