Complete API reference for the Firefly Common Cache Library.
Package: org.fireflyframework.cache.manager.FireflyCacheManager
The main entry point for cache operations. Manages multiple cache instances and provides a unified API.
public FireflyCacheManager()
public FireflyCacheManager(CacheSelectionStrategy selectionStrategy, String defaultCacheName)Retrieve a value from the default cache.
public <K, V> Mono<Optional<V>> get(K key)
public <K, V> Mono<Optional<V>> get(K key, Class<V> valueType)Parameters:
key: The cache keyvalueType: Expected value type (for type-safe retrieval)
Returns: Mono<Optional<V>> containing the value if present
Example:
cacheManager.get("user:123", User.class)
.subscribe(optionalUser -> {
if (optionalUser.isPresent()) {
User user = optionalUser.get();
// Use user
}
});Store a value in the default cache.
public <K, V> Mono<Void> put(K key, V value)
public <K, V> Mono<Void> put(K key, V value, Duration ttl)Parameters:
key: The cache keyvalue: The value to storettl: Time-to-live (optional)
Returns: Mono<Void> that completes when stored
Example:
User user = new User("123", "John");
cacheManager.put("user:123", user, Duration.ofMinutes(30))
.subscribe();Store a value only if the key doesn't exist.
public <K, V> Mono<Boolean> putIfAbsent(K key, V value)
public <K, V> Mono<Boolean> putIfAbsent(K key, V value, Duration ttl)Parameters:
key: The cache keyvalue: The value to storettl: Time-to-live (optional)
Returns: Mono<Boolean> - true if stored, false if key existed
Example:
cacheManager.putIfAbsent("lock:resource", "locked", Duration.ofSeconds(30))
.subscribe(wasStored -> {
if (wasStored) {
// Lock acquired
} else {
// Lock already held
}
});Remove a value from the default cache.
public <K> Mono<Boolean> evict(K key)Parameters:
key: The cache key to remove
Returns: Mono<Boolean> - true if removed, false if not found
Example:
cacheManager.evict("user:123")
.subscribe(removed -> {
if (removed) {
log.info("User cache entry removed");
}
});Remove all entries from the default cache.
public Mono<Void> clear()Returns: Mono<Void> that completes when cleared
Example:
cacheManager.clear()
.subscribe(() -> log.info("Cache cleared"));Check if a key exists in the default cache.
public <K> Mono<Boolean> exists(K key)Parameters:
key: The cache key to check
Returns: Mono<Boolean> - true if exists
Example:
cacheManager.exists("user:123")
.subscribe(exists -> {
if (exists) {
log.info("User is cached");
}
});All operations have named cache variants:
public <K, V> Mono<Optional<V>> get(String cacheName, K key)
public <K, V> Mono<Void> put(String cacheName, K key, V value)
public <K> Mono<Boolean> evict(String cacheName, K key)
public Mono<Void> clear(String cacheName)Example:
cacheManager.put("user-cache", "123", user)
.subscribe();Register a cache adapter with the manager.
public void registerCache(String name, CacheAdapter adapter)Parameters:
name: Cache nameadapter: Cache adapter instance
Example:
CaffeineCacheAdapter adapter = new CaffeineCacheAdapter("my-cache", config);
cacheManager.registerCache("my-cache", adapter);Unregister and close a cache adapter.
public CacheAdapter unregisterCache(String name)Parameters:
name: Cache name to unregister
Returns: The removed adapter, or null if not found
Get a cache adapter by name.
public CacheAdapter getCache(String name)Parameters:
name: Cache name
Returns: The cache adapter, or null if not found
Get all registered cache names.
public Set<String> getCacheNames()Returns: Set of cache names
Check if a cache is registered.
public boolean hasCache(String name)Parameters:
name: Cache name
Returns: true if registered
Get health information for all or specific cache.
public Flux<CacheHealth> getHealth()
public Mono<CacheHealth> getHealth(String cacheName)Returns: Health information
Example:
cacheManager.getHealth()
.subscribe(health -> {
log.info("Cache: {}, Status: {}",
health.getCacheName(),
health.getStatus());
});Get statistics for all or specific cache.
public Flux<CacheStats> getStats()
public Mono<CacheStats> getStats(String cacheName)Returns: Cache statistics
Example:
cacheManager.getStats("default")
.subscribe(stats -> {
log.info("Hit rate: {}%", stats.getHitRate() * 100);
log.info("Hits: {}, Misses: {}",
stats.getHitCount(),
stats.getMissCount());
});Close the cache manager and all registered caches.
public void close()Example:
@PreDestroy
public void cleanup() {
cacheManager.close();
}Package: org.fireflyframework.cache.core.CacheAdapter
Interface defining cache operations. Implemented by cache providers.
// Retrieve
<K, V> Mono<Optional<V>> get(K key)
<K, V> Mono<Optional<V>> get(K key, Class<V> valueType)
// Store
<K, V> Mono<Void> put(K key, V value)
<K, V> Mono<Void> put(K key, V value, Duration ttl)
// Conditional store
<K, V> Mono<Boolean> putIfAbsent(K key, V value)
<K, V> Mono<Boolean> putIfAbsent(K key, V value, Duration ttl)
// Remove
<K> Mono<Boolean> evict(K key)
Mono<Void> clear()
// Query
<K> Mono<Boolean> exists(K key)
<K> Mono<Set<K>> keys()
Mono<Long> size()
// Monitoring
Mono<CacheStats> getStats()
Mono<CacheHealth> getHealth()
// Metadata
CacheType getCacheType()
String getCacheName()
boolean isAvailable()
// Lifecycle
void close()- CaffeineCacheAdapter: In-memory cache using Caffeine
- RedisCacheAdapter: Distributed cache using Redis
Package: org.fireflyframework.cache.annotation
Note: Annotations are defined but aspect implementation is not yet complete. Use programmatic API for production.
Enable cache annotation processing.
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EnableCaching {
boolean proxyTargetClass() default false;
AdviceMode mode() default AdviceMode.PROXY;
int order() default Integer.MAX_VALUE;
}Usage:
@Configuration
@EnableCaching
public class CacheConfig {
}Mark methods whose results should be cached.
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Cacheable {
String[] value() default {"default"};
String[] cacheNames() default {};
String key() default "";
String keyGenerator() default "";
String condition() default "";
String unless() default "";
String ttl() default "";
boolean sync() default false;
}Attributes:
value/cacheNames: Cache names to usekey: SpEL expression for cache keycondition: SpEL condition for cachingunless: SpEL condition to prevent cachingttl: Time-to-live (ISO-8601 format)sync: Synchronize concurrent calls
Example:
@Cacheable(value = "users", key = "#userId", ttl = "PT30M")
public Mono<User> getUser(String userId) {
return userRepository.findById(userId);
}Mark methods that should trigger cache eviction.
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CacheEvict {
String[] value() default {"default"};
String[] cacheNames() default {};
String key() default "";
String condition() default "";
boolean allEntries() default false;
boolean beforeInvocation() default false;
}Attributes:
value/cacheNames: Cache nameskey: SpEL expression for cache keycondition: SpEL condition for evictionallEntries: Evict all entriesbeforeInvocation: Evict before method execution
Example:
@CacheEvict(value = "users", key = "#user.id")
public Mono<User> updateUser(User user) {
return userRepository.save(user);
}Mark methods that should always update the cache.
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CachePut {
String[] value() default {"default"};
String[] cacheNames() default {};
String key() default "";
String keyGenerator() default "";
String condition() default "";
String unless() default "";
String ttl() default "";
}Example:
@CachePut(value = "users", key = "#result.id")
public Mono<User> createUser(User user) {
return userRepository.save(user);
}Group multiple cache operations.
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Caching {
Cacheable[] cacheable() default {};
CachePut[] put() default {};
CacheEvict[] evict() default {};
}Example:
@Caching(
evict = {
@CacheEvict(value = "users", key = "#user.id"),
@CacheEvict(value = "userList", allEntries = true)
}
)
public Mono<Void> deleteUser(User user) {
return userRepository.delete(user);
}Package: org.fireflyframework.cache.properties.CacheProperties
Main configuration properties class.
@ConfigurationProperties(prefix = "firefly.cache")
public class CacheProperties {
private boolean enabled = true;
private CacheType defaultCacheType = CacheType.CAFFEINE;
private String defaultCacheName = "default";
private boolean metricsEnabled = true;
private boolean healthEnabled = true;
private Map<String, CacheConfig> caches;
private Map<String, CaffeineConfig> caffeine;
private Map<String, RedisConfig> redis;
}Package: org.fireflyframework.cache.adapter.caffeine.CaffeineCacheConfig
Caffeine cache configuration.
@Builder
public class CaffeineCacheConfig {
private final Long maximumSize;
private final Duration expireAfterWrite;
private final Duration expireAfterAccess;
private final Duration refreshAfterWrite;
private final boolean recordStats;
private final boolean weakKeys;
private final boolean weakValues;
private final boolean softValues;
}Package: org.fireflyframework.cache.adapter.redis.RedisCacheConfig
Redis cache configuration.
@Builder
public class RedisCacheConfig {
private final String host;
private final int port;
private final int database;
private final String password;
private final String username;
private final Duration connectionTimeout;
private final Duration commandTimeout;
private final String keyPrefix;
private final Duration defaultTtl;
private final int maxPoolSize;
private final int minPoolSize;
private final boolean ssl;
}Package: org.fireflyframework.cache.core.CacheHealth
Cache health information.
public class CacheHealth {
private final CacheType cacheType;
private final String cacheName;
private final HealthStatus status;
private final boolean available;
private final boolean configured;
private final long responseTimeMs;
private final String message;
private final Throwable error;
}Package: org.fireflyframework.cache.core.CacheStats
Cache statistics.
public class CacheStats {
private final CacheType cacheType;
private final String cacheName;
private final long hitCount;
private final long missCount;
private final long loadSuccessCount;
private final long loadFailureCount;
private final long evictionCount;
private final long size;
public double getHitRate() {
long total = hitCount + missCount;
return total == 0 ? 0.0 : (double) hitCount / total;
}
}Package: org.fireflyframework.cache.exception.CacheException
Base exception for cache operations.
public class CacheException extends RuntimeException {
public CacheException(String message)
public CacheException(String message, Throwable cause)
}Package: org.fireflyframework.cache.serialization.SerializationException
Exception for serialization errors.
public class SerializationException extends CacheException {
public SerializationException(String message, Throwable cause)
}