Enhanced Client-side caching
We've substantially improved server-assisted, client-side caching in response to user feedback. It is currently a beta grade.
Client-side caching is supported exclusively with the RESP3 protocol and is available in UnifiedJedis, JedisPooled, and JedisCluster and other classes.
How to try Client-Side Caching
- Install Jedis 5.2.0-beta5
- Use the following code example to get started:
public class CSCExampleTest {
public static void main() {
HostAndPort node = HostAndPort.from("localhost:6379");
JedisClientConfig clientConfig = DefaultJedisClientConfig.builder()
.resp3() // RESP3 protocol is required for client-side caching
//.user("myuser") // Redis server username (optional)
//.password("mypass") // Redis user's password (optional)
.build();
CacheConfig cacheConfig = getCacheConfig();
Cache cache = CacheFactory.getCache(cacheConfig);
try (UnifiedJedis client = new UnifiedJedis(node, clientConfig, cache)) {
client.set("foo", "bar");
client.get("foo");
client.get("foo"); // Cache hit
System.out.println("Cache size: " + cache.getSize()); // 1
System.out.println(cache.getStats().toString());
//Let's change the value of "foo" to invalidate the value stored in the local cache
client.mset("foo", "new_value", "ignore_me:1", "another_value");
Thread.sleep(1000); // wait for the cache invalidation to happen
System.out.println(client.get("foo")); // Cache miss
System.out.println(cache.getStats().toString());
client.get("ignore_me:1"); // Client will ignore this key
System.out.println("Cache size: " + cache.getSize()); // still 1
// check the cache stats
System.out.println(cache.getStats().toString());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private static CacheConfig getCacheConfig() {
// This is a simple cacheable implementation that ignores keys starting with "ignore_me"
Cacheable cacheable = new DefaultCacheable() {
final String IGNORE_PREFIX = "ignore_me";
@Override
public boolean isCacheable(ProtocolCommand command, List<Object> keys) {
// assuming we'll only execute methods with string keys
List<String> stringKeys = keys.stream()
.filter(obj -> obj instanceof String)
.map(obj -> (String) obj)
.collect(Collectors.toList());
for (String key : stringKeys) {
if (key.startsWith(IGNORE_PREFIX)) {
return false;
}
}
return isDefaultCacheableCommand(command);
}
};
// Create a cache with a maximum size of 10000 entries
return CacheConfig.builder()
.maxSize(10000)
.cacheable(cacheable)
.build();
}
}
It is possible to limit or ignore commands or keys for client-side caching. The getCacheConfig
method presented above provides an example of how to achieve that.