Memcached
medium 30 minMemcached is a small, fast, shared cache for plain values.
A tiny Memcached: classes, eviction, add and cas
Read it, run it, change a line and run it again.
Loading editor…
A model for understanding, with pages of 1,000 bytes. It runs without Memcached.
The same in Java
// net.spy:spymemcached. ASCII protocol and Ketama hashing.import java.net.InetSocketAddress;import java.util.*;import java.util.concurrent.*;import java.util.function.UnaryOperator;import net.spy.memcached.*;public class MemcachedExamples { private final MemcachedClient client; public MemcachedExamples() throws Exception { ConnectionFactory factory = new ConnectionFactoryBuilder() .setProtocol(ConnectionFactoryBuilder.Protocol.TEXT) .setLocatorType(ConnectionFactoryBuilder.Locator.CONSISTENT) .setHashAlg(DefaultHashAlgorithm.KETAMA_HASH) .setFailureMode(FailureMode.Redistribute) .setOpTimeout(500) .setMaxReconnectDelay(30) .build(); client = new MemcachedClient(factory, List.of( new InetSocketAddress("mc1", 11211), new InetSocketAddress("mc2", 11211), new InetSocketAddress("mc3", 11211))); } boolean set(String key, int ttl, Object value) { Future<Boolean> f = client.set(key, ttl, value); // asynchronous try { return f.get(500, TimeUnit.MILLISECONDS); } catch (Exception e) { f.cancel(false); return false; // a cache may fail } } Object get(String key) { Future<Object> f = client.asyncGet(key); try { return f.get(500, TimeUnit.MILLISECONDS); } catch (Exception e) { f.cancel(false); return null; } } Map<String, Object> getMany(Collection<String> keys) { // asked in parallel return client.getBulk(keys); } boolean update(String key, int ttl, UnaryOperator<Object> change) { for (int i = 0; i < 5; i++) { CASValue<Object> now = client.gets(key); if (now == null) return false; CASResponse r = client.cas(key, now.getCas(), ttl, change.apply(now.getValue())); if (r == CASResponse.OK) return true; // EXISTS: changed, try again } return false; } long count(String key, int ttl) { return client.incr(key, 1, 1, ttl); } void close() { client.shutdown(10, TimeUnit.SECONDS); }}