Class RedisService
- Namespace
- adas_core.Application.Services.Caching
- Assembly
- adas-core.Application.dll
Represents a Redis-based implementation of the ICacheService interface for caching operations.
public class RedisService : ICacheService
- Inheritance
-
RedisService
- Implements
- Inherited Members
- Extension Methods
Constructors
RedisService(IOptions<CacheSettings>, ILogger<RedisService>, LockManagerService)
public RedisService(IOptions<CacheSettings> options, ILogger<RedisService> logger, LockManagerService lockManager)
Parameters
optionsIOptions<CacheSettings>loggerILogger<RedisService>lockManagerLockManagerService
Properties
Database
public IDatabase? Database { get; }
Property Value
- IDatabase
Methods
CleanCache()
Clears all cached data by flushing the underlying server database. If the server instance is null, the call is safely skipped as a no-op.
public void CleanCache()
DeleteByPatternAsync(string)
Asynchronously deletes all Redis keys matching the specified pattern. Returns 0 if Redis is unavailable or the server is not initialized.
public Task<long> DeleteByPatternAsync(string pattern)
Parameters
patternstringThe pattern used to match Redis keys to be deleted.
Returns
DeleteObjectAsync(string)
Asynchronously deletes an object from the Redis cache using the specified key. When the Redis backend is unavailable, the call is skipped silently as a no-op fallback.
public Task DeleteObjectAsync(string key)
Parameters
keystringThe unique identifier of the cached object to remove.
Returns
GetObjectAsync<T>(string, bool)
Asynchronously retrieves and deserializes an object of type T from Redis using the specified key.
Returns default when Redis is unavailable or when the key is not found or holds an empty value, and optionally refreshes the key's expiration time on a successful hit.
public Task<T?> GetObjectAsync<T>(string key, bool updateExpiration = true)
Parameters
keystringThe Redis key identifying the stored object to retrieve.
updateExpirationboolWhen
true(the default), resets the key's time-to-live to the configured entity TTL on a successful read, implementing sliding expiration.
Returns
- Task<T>
A Task<TResult> containing the deserialized object, or
defaultif Redis is unavailable or the key is missing/empty.
Type Parameters
T
Exceptions
- Exception
Thrown when the stored JSON payload cannot be deserialized into
T; the original exception is wrapped and rethrown.
GetObjectAsync<T>(string, TimeSpan?, bool)
Retrieves an object asynchronously from the cache, optionally updating its expiration time. The optional TTL override is ignored by this overload and is not passed to the underlying call.
public Task<T?> GetObjectAsync<T>(string key, TimeSpan? ttlOverride, bool updateExpiration)
Parameters
keystringThe cache key identifying the object to retrieve.
ttlOverrideTimeSpan?An optional time-to-live override; not applied by this overload.
updateExpirationboolWhen true, the expiration of the cached entry is refreshed on retrieval.
Returns
- Task<T>
A task that resolves to the cached object, or null if no entry exists for the specified key.
Type Parameters
T
GetOrSetObjectAsync<T>(string, Func<Task<T>>, TimeSpan?, CancellationToken)
Retrieves an object of type T from the cache using the specified key, or creates and caches a new instance using the provided factory if no cached value exists. Uses a distributed lock to prevent concurrent cache misses from creating duplicate objects, and falls back to calling the factory directly when Redis is unavailable.
public Task<T> GetOrSetObjectAsync<T>(string key, Func<Task<T>> factory, TimeSpan? ttl = null, CancellationToken cancellationToken = default)
Parameters
keystringThe cache key used to identify the stored object.
factoryFunc<Task<T>>The asynchronous factory function invoked to create a new instance when the object is not present in the cache.
ttlTimeSpan?Optional time-to-live duration for the cached object. If null, the cache default is used.
cancellationTokenCancellationTokenThe token used to cancel the asynchronous operation.
Returns
- Task<T>
A task that represents the asynchronous operation, containing the cached or newly created object.
Type Parameters
T
GetOrSetObjectAsync<T>(GroupedField, ObjectId, Func<Task<T>>, TimeSpan?, CancellationToken)
Retrieves a cached object associated with the specified grouped field and patient identifier, or creates and stores it using the provided factory if absent. Uses a distributed lock to prevent duplicate creation under cache misses and falls back to invoking the factory directly when Redis is unavailable.
public Task<T> GetOrSetObjectAsync<T>(GroupedField groupedField, ObjectId patientId, Func<Task<T>> factory, TimeSpan? ttl = null, CancellationToken cancellationToken = default)
Parameters
groupedFieldGroupedFieldThe grouped field used, together with the patient identifier, to build the cache key.
patientIdObjectIdThe patient identifier used to build the cache key.
factoryFunc<Task<T>>Asynchronous factory invoked to produce the object when no cached value exists.
ttlTimeSpan?Optional time-to-live applied to the stored cache entry. If null, no expiration is set.
cancellationTokenCancellationTokenToken used to cancel the distributed lock operation.
Returns
- Task<T>
The cached object if present, otherwise the object produced by
factory.
Type Parameters
T
GetOrSetValueAsync(string, Func<Task<string>>, TimeSpan?)
Retrieves a cached value for the specified key, or loads, caches, and returns it via the supplied loader if absent. Falls back to invoking the loader directly when Redis is unavailable, and uses a distributed lock to prevent duplicate loads under concurrent access.
public Task<string?> GetOrSetValueAsync(string key, Func<Task<string>> loader, TimeSpan? ttl = null)
Parameters
keystringThe cache key used to identify the stored value.
loaderFunc<Task<string>>The asynchronous function invoked to produce the value when it is not present in the cache.
ttlTimeSpan?Optional time-to-live applied to the cached value; if not provided, the default caching policy is used.
Returns
- Task<string>
The cached value when available, or the value produced by the loader when the cache is empty or Redis is unavailable.
GetValue(string)
Retrieves a string value from the underlying data store by its key, and conditionally renews the entity's time-to-live when the key is found and renewal is permitted by policy.
public string? GetValue(string key)
Parameters
keystringThe identifier of the value to look up in the data store.
Returns
- string
The stored string value, or
nullif the key does not exist or the data store is unavailable.
SetObjectAsync<T>(string, T, bool)
Asynchronously stores an object associated with the specified key, optionally refreshing its expiration time.
public Task SetObjectAsync<T>(string key, T obj, bool updateExpiration = true)
Parameters
keystringThe key under which the object will be stored.
objTThe object to store.
updateExpirationboolIndicates whether the expiration time of the entry should be updated.
Returns
Type Parameters
T
SetObjectAsync<T>(string, T, TimeSpan?, bool)
Asynchronously serializes the specified object to JSON and stores it in Redis under the given key, using the provided TTL override or the default entity TTL when not specified. The operation is skipped when Redis is unavailable, and the object is serialized using camelCase property names with string enum and ObjectId converters.
public Task SetObjectAsync<T>(string key, T obj, TimeSpan? ttlOverride, bool updateExpiration)
Parameters
keystringThe Redis key under which the serialized object will be stored.
objTThe object to serialize and persist to Redis.
ttlOverrideTimeSpan?An optional time-to-live override; when null, the entity's default TTL is applied.
updateExpirationboolFlag indicating whether the expiration should be updated.
Returns
Type Parameters
T
SetValue(string, string)
Stores a string value in the database under the specified key, applying a TTL resolved from GetEntityTtl and preserving any existing TTL on overwrite. If the underlying database is not initialized, the operation is skipped.
public void SetValue(string key, string value)