put method
Stores a value in the cache with a specified time-to-live (TTL).
The key is a unique identifier for the cached item. The value can be
any dynamic type, and it will be stored for the duration specified by ttl.
After the TTL expires, the item may be automatically removed from the cache.
Throws an exception if the key is null or empty, or if ttl is negative.
Implementations should handle serialization of complex value types if needed.
- Parameters:
key: A non-null, non-empty string representing the cache key.value: The data to be cached, which can be of any type.ttl: The duration for which the item should remain in the cache.
Implementation
@override
Future<void> put(String key, dynamic value, Duration ttl) async {
if (key.isEmpty) {
throw ArgumentError('Cache key cannot be empty');
}
if (ttl.isNegative) {
throw ArgumentError('TTL duration cannot be negative');
}
try {
final serializedValue = jsonEncode(value);
// Use PX (milliseconds) for small TTLs, EX (seconds) for larger ones
final ttlInSeconds = ttl.inSeconds;
final ttlInMilliseconds = ttl.inMilliseconds;
List<Object> command;
if (ttlInSeconds == 0 && ttlInMilliseconds > 0) {
// For TTLs less than 1 second, use PX (milliseconds)
command = ['SET', key, serializedValue, 'PX', ttlInMilliseconds];
} else if (ttlInSeconds > 0) {
// For TTLs of 1 second or more, use EX (seconds)
command = ['SET', key, serializedValue, 'EX', ttlInSeconds];
} else {
// TTL is zero or negative (shouldn't happen due to validation above)
command = ['SET', key, serializedValue];
}
await _executeCommand(command, isWrite: true);
} catch (e) {
throw CacheException('Failed to store cache item "$key": $e');
}
}