RedisCacheDriver class

Redis-based cache driver implementation for the Khadem framework.

This driver provides high-performance, distributed caching using Redis as the underlying storage backend. It's ideal for applications that need shared caching across multiple instances or processes.

Key Features

  • High Performance: Fast O(1) operations using Redis in-memory storage
  • Distributed: Shared cache across multiple application instances
  • Persistence: Optional Redis persistence for cache durability
  • TTL Support: Automatic expiration of cache entries
  • Statistics Tracking: Built-in performance metrics
  • Connection Pooling: Efficient connection management
  • Error Handling: Robust error handling with graceful degradation
  • Configuration: Flexible Redis connection settings

Usage

// Create a Redis cache driver with default settings
final cache = RedisCacheDriver();

// Create with custom settings
final cache = RedisCacheDriver(
  host: 'redis.example.com',
  port: 6379,
  password: 'secret',
  database: 1,
);

// Store data with TTL
await cache.put('user:123', {'name': 'John', 'email': 'john@example.com'}, Duration(hours: 1));

// Retrieve data
final user = await cache.get('user:123');

// Check if key exists
final exists = await cache.has('user:123');

// Remove specific key
await cache.forget('user:123');

// Clear all cache
await cache.clear();

// Get cache statistics
final stats = cache.getStats();
print('Hit rate: ${stats.hitRate}%');

Configuration Options

  • host: Redis server hostname (default: 'localhost')
  • port: Redis server port (default: 6379)
  • password: Redis server password (optional)
  • database: Redis database number (default: 0)
  • maxRetries: Maximum connection retry attempts (default: 3)
  • retryDelay: Delay between retry attempts (default: 100ms)

Performance Characteristics

  • put(): O(1) - Constant time insertion
  • get(): O(1) - Constant time retrieval
  • has(): O(1) - Constant time existence check
  • forget(): O(1) - Constant time deletion
  • clear(): O(n) - Linear time for all entries in database

Connection Management

The driver maintains a connection pool and automatically reconnects on failures. Connections are reused across operations for optimal performance.

Error Handling

The driver gracefully handles Redis connection failures and network issues. Failed operations are logged and statistics are updated accordingly.

Thread Safety

This implementation is thread-safe and can be used concurrently from multiple isolates, though each isolate will maintain its own connection pool.

Implemented types

Constructors

RedisCacheDriver({String host = 'localhost', int port = 6379, String? password, int database = 0, int maxRetries = 3, Duration retryDelay = const Duration(milliseconds: 100)})
Creates a new RedisCacheDriver instance.

Properties

database int
Redis database number
final
hashCode int
The hash code for this object.
no setterinherited
host String
Redis server hostname
final
maxRetries int
Maximum number of connection retry attempts
final
password String?
Redis server password (optional)
final
port int
Redis server port
final
retryDelay Duration
Delay between retry attempts
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

add(String key, dynamic value, Duration ttl) Future<bool>
Stores a value in the cache if the key does not exist.
override
clear() Future<void>
Clears all items from the cache.
override
decrement(String key, [int amount = 1]) Future<int>
Decrement the value of an item in the cache.
override
dispose() Future<void>
Closes the Redis connection and cleans up resources.
forget(String key) Future<void>
Removes a value from the cache by its key.
override
get(String key) Future
Retrieves a value from the cache by its key.
override
getStats() CacheStats
Gets cache statistics.
has(String key) Future<bool>
Checks if a key exists in the cache and has not expired.
override
increment(String key, [int amount = 1]) Future<int>
Increment the value of an item in the cache.
override
many(List<String> keys) Future<Map<String, dynamic>>
Retrieves multiple values from the cache by their keys.
override
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
pull(String key) Future
Retrieve an item from the cache and delete it.
override
put(String key, dynamic value, Duration ttl) Future<void>
Stores a value in the cache with a specified time-to-live (TTL).
override
putMany(Map<String, dynamic> values, Duration ttl) Future<void>
Stores multiple values in the cache.
override
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited