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
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With