Package dev.cachly
Class CachlyClient
java.lang.Object
dev.cachly.CachlyClient
- All Implemented Interfaces:
Closeable,AutoCloseable
Official Java client for cachly.dev managed
Valkey/Redis instances.
Wraps Jedis with a typed API and optional semantic AI caching. Thread-safe – one instance per application is recommended.
Quick start
try (CachlyClient cache = CachlyClient.connect(System.getenv("CACHLY_URL"))) {
// Simple key/value
cache.set("user:42", Map.of("name", "Alice"), 300);
Map<?,?> user = cache.get("user:42", Map.class);
// Semantic AI cache with pgvector API (Speed / Business tiers)
SemanticResult<String> result = cache.semantic().getOrSet(
question,
() -> openAi.ask(question),
text -> openAi.embed(text),
0.92
);
System.out.println(result.isHit() ? "⚡ hit" : "🔄 miss");
}
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final classA single operation forbatch(java.util.List<dev.cachly.CachlyClient.BatchOp>).static final classResult of a single operation in abatch(java.util.List<dev.cachly.CachlyClient.BatchOp>)call.static final classstatic final classOne entry forbulkWarmup(java.util.List<dev.cachly.CachlyClient.BulkWarmupEntry>)(feature S).static final classResult ofbulkWarmup(java.util.List<dev.cachly.CachlyClient.BulkWarmupEntry>)(feature S).static final classResult ofinvalidateTag(java.lang.String)(feature M).static final classResult ofllmProxyStats()(feature W).final classHandle returned by a successfullock(java.lang.String, long, int, long)call.static final classOne item in a bulkmset(java.util.List<dev.cachly.CachlyClient.MSetItem>)call.static final classResult ofswrCheck()(feature Q).static final classOne SWR key entry (feature Q).static final classResult ofsetTags(java.lang.String, java.util.List<java.lang.String>)(feature L). -
Method Summary
Modifier and TypeMethodDescriptionbatch(List<CachlyClient.BatchOp> ops) Execute multiple cache operations in a single round-trip.static CachlyClient.BuilderFluent builder for constructing aCachlyClientwith all optional URLs.bulkWarmup(List<CachlyClient.BulkWarmupEntry> entries) KV Bulk-Warmup via server-side pipeline (S).voidclose()static CachlyClientConnect to a cachly instance by URL (no pgvector API).static CachlyClientConnect to a cachly instance with pgvector API support (HNSW O(log n)).static CachlyClientConnect to a cachly instance with full API support.longDelete one or more keys.booleandeleteTags(String key) Remove all tags for a cache key (O).edge()Return anEdgeCacheClientfor managing Cloudflare Edge Cache (feature #5).booleanCheck whether a key exists.voidUpdate TTL for an existing key.<T> TRetrieve a value by key and deserialize totype.<T> TGet-or-set without TTL.<T> TGet-or-set: return cached value or callfn, cache and return.Get all tags for a cache key (N).longAtomically increment a counter.invalidateTag(String tag) Delete all cache keys for a tag (M).LLM cache proxy statistics (W).Acquire a distributed lock with default retry settings (3 retries, 50 ms delay).Acquire a distributed lock using Redis SET NX PX (Redlock-lite pattern).<T> List<T> Retrieve multiple keys in one round-trip (native MGET).voidmset(List<CachlyClient.MSetItem> items) Set multiple key-value pairs in a single pipeline round-trip.booleanping()Check connectivity to the cache server.pubsub()Return aPubSubClientfor real-time messaging (feature U).redis.clients.jedis.UnifiedJedisraw()Direct access to the underlying Jedis client for advanced operations.semantic()Access theSemanticCachehelper.voidStore a value without TTL.voidStore a value as JSON.Associate a cache key with tags (max 50) (L).Retrieve a cached stream as a lazyIterator<String>.voidCache a streaming response without TTL.voidCache a streaming response chunk-by-chunk via Redis RPUSH.swrCheck()Return all keys currently stale (Q).booleanswrRegister(String key, int ttlSeconds, int staleWindowSeconds) booleanswrRegister(String key, int ttlSeconds, int staleWindowSeconds, String fetcherHint) Register a key for Stale-While-Revalidate (P).booleanRemove a key from the SWR registry (R).longReturn the remaining TTL for a key in seconds.workflow()Return aWorkflowClientfor agent workflow checkpoints (feature V).
-
Method Details
-
connect
Connect to a cachly instance by URL (no pgvector API).- Parameters:
url- Redis connection URL:redis://:password@host:port
-
connect
Connect to a cachly instance with pgvector API support (HNSW O(log n)).- Parameters:
url- Redis connection URL:redis://:password@host:portvectorUrl- pgvector API URL:https://api.cachly.dev/v1/sem/{token}Passnullto disable API mode (falls back to SCAN).
-
connect
Connect to a cachly instance with full API support.- Parameters:
url- Redis connection URL:redis://:password@host:portvectorUrl- pgvector API URL (ornull).batchUrl- KV Batch API URL:https://api.cachly.dev/v1/cache/{token}When set,batch(java.util.List<dev.cachly.CachlyClient.BatchOp>)sends all ops in one HTTP request.
-
get
Retrieve a value by key and deserialize totype.- Returns:
- deserialized value, or
nullwhen not found
-
set
Store a value as JSON. PassttlSeconds > 0for automatic expiry. -
set
Store a value without TTL. -
del
Delete one or more keys.- Returns:
- number of keys deleted
-
exists
Check whether a key exists. -
expire
Update TTL for an existing key.- Parameters:
seconds- new TTL in seconds
-
ttl
Return the remaining TTL for a key in seconds.- Returns:
- seconds remaining;
-1if no TTL;-2if key not found
-
ping
public boolean ping()Check connectivity to the cache server.- Returns:
trueif the server is reachable and responds to PING
-
incr
Atomically increment a counter.- Returns:
- new value after increment
-
getOrSet
Get-or-set: return cached value or callfn, cache and return.- Parameters:
ttlSeconds- TTL for newly cached entry;0= no expiry
-
getOrSet
Get-or-set without TTL. -
mset
Set multiple key-value pairs in a single pipeline round-trip. Supports per-key TTL – unlike native MSET which has no expiry option.cache.mset(List.of( new CachlyClient.MSetItem("user:1", Map.of("name", "Alice"), 300), new CachlyClient.MSetItem("user:2", Map.of("name", "Bob")) )); -
mget
Retrieve multiple keys in one round-trip (native MGET). Returns a list in the same order askeys; missing keys returnnull.List<String> vals = cache.mget(List.of("user:1", "user:2"), String.class);- Type Parameters:
T- target type for each value- Parameters:
keys- list of keys to fetchtype- class to deserialize each value into- Returns:
- list of values (null for missing keys)
-
lock
Acquire a distributed lock using Redis SET NX PX (Redlock-lite pattern).Returns a
CachlyClient.LockHandleon success, ornullwhen all attempts are exhausted. The lock auto-expires afterttlMsto prevent deadlocks.try (CachlyClient.LockHandle lock = cache.lock("job:42", 5000, 5)) { if (lock == null) throw new IllegalStateException("Busy"); processJob(); }- Parameters:
key- Resource identifier (prefixed withcachly:lock:).ttlMs- Safety TTL in milliseconds.retries- Max acquire attempts (default 3).retryDelayMs- Milliseconds between retries (default 50).- Returns:
- LockHandle or
null
-
lock
Acquire a distributed lock with default retry settings (3 retries, 50 ms delay). -
batch
Execute multiple cache operations in a single round-trip.When
batchUrlis configured (pass toconnect(String, String, String)), all ops are sent viaPOST {batchUrl}/batch(one HTTP request). Otherwise they fall back to a Jedis pipeline.List<CachlyClient.BatchOpResult> results = cache.batch(List.of( CachlyClient.BatchOp.get("user:1"), CachlyClient.BatchOp.get("config:app"), CachlyClient.BatchOp.set("visits", Long.toString(System.currentTimeMillis()), 86400), )); String user = results.get(0).value; // null if not found String config = results.get(1).value; boolean ok = results.get(2).ok; -
streamSet
Cache a streaming response chunk-by-chunk via Redis RPUSH.After all chunks are stored, an optional TTL is set on the list key. Replay stored chunks with
streamGet(String).- Parameters:
key- Cache key.chunks- Iterable of string chunks (e.g. LLM token stream).ttlSeconds- TTL in seconds;0= no expiry.
-
streamSet
Cache a streaming response without TTL. -
streamGet
Retrieve a cached stream as a lazyIterator<String>.Returns
nullon a cache miss (key absent or empty list). The iterator fetches chunks one-by-one via LINDEX.Iterator<String> cached = cache.streamGet("chat:42"); if (cached != null) { while (cached.hasNext()) response.write(cached.next()); } -
semantic
Access theSemanticCachehelper. Available on Speed and Business tiers. -
pubsub
Return aPubSubClientfor real-time messaging (feature U). RequirespubsubUrlviaCachlyClient.Builder.pubsubUrl(String). -
workflow
Return aWorkflowClientfor agent workflow checkpoints (feature V). RequiresworkflowUrlviaCachlyClient.Builder.workflowUrl(String). -
edge
Return anEdgeCacheClientfor managing Cloudflare Edge Cache (feature #5). RequiresedgeApiUrlviaCachlyClient.Builder.edgeApiUrl(String).- Returns:
- EdgeCacheClient for config, purge, and stats operations
- Throws:
CachlyException- if edgeApiUrl was not configured
-
setTags
Associate a cache key with tags (max 50) (L). RequiresbatchUrl. -
invalidateTag
Delete all cache keys for a tag (M). RequiresbatchUrl. -
getTags
Get all tags for a cache key (N). RequiresbatchUrl. -
deleteTags
Remove all tags for a cache key (O). RequiresbatchUrl. -
swrRegister
Register a key for Stale-While-Revalidate (P). RequiresbatchUrl. -
swrRegister
-
swrCheck
Return all keys currently stale (Q). RequiresbatchUrl. -
swrRemove
Remove a key from the SWR registry (R). RequiresbatchUrl. -
bulkWarmup
KV Bulk-Warmup via server-side pipeline (S). RequiresbatchUrl. -
llmProxyStats
LLM cache proxy statistics (W). RequiresllmProxyUrl. -
builder
Fluent builder for constructing aCachlyClientwith all optional URLs.CachlyClient client = CachlyClient.builder(System.getenv("CACHLY_URL")) .vectorUrl(System.getenv("CACHLY_VECTOR_URL")) .batchUrl(System.getenv("CACHLY_BATCH_URL")) .pubsubUrl(System.getenv("CACHLY_PUBSUB_URL")) .workflowUrl(System.getenv("CACHLY_WORKFLOW_URL")) .build(); -
raw
public redis.clients.jedis.UnifiedJedis raw()Direct access to the underlying Jedis client for advanced operations. -
close
public void close()- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable
-