using System.Net; using Microsoft.Extensions.Caching.Distributed; using Nop.Core.Caching; using Nop.Core.Configuration; using Nop.Core.Infrastructure; using StackExchange.Redis; namespace Nop.Services.Caching; /// /// Represents a redis distributed cache /// public partial class RedisCacheManager : DistributedCacheManager { #region Fields protected readonly IRedisConnectionWrapper _connectionWrapper; #endregion #region Ctor public RedisCacheManager(AppSettings appSettings, IDistributedCache distributedCache, IRedisConnectionWrapper connectionWrapper, ICacheKeyManager cacheKeyManager, IConcurrentCollection concurrentCollection) : base(appSettings, distributedCache, cacheKeyManager, concurrentCollection) { _connectionWrapper = connectionWrapper; } #endregion #region Utilities /// /// Gets the list of cache keys prefix /// /// Network address /// String key pattern /// List of cache keys protected virtual async Task> GetKeysAsync(EndPoint endPoint, string prefix = null) { return await (await _connectionWrapper.GetServerAsync(endPoint)) .KeysAsync((await _connectionWrapper.GetDatabaseAsync()).Database, string.IsNullOrEmpty(prefix) ? null : $"{prefix}*") .ToListAsync(); } #endregion #region Methods /// /// Remove items by cache key prefix /// /// Cache key prefix /// Parameters to create cache key prefix /// A task that represents the asynchronous operation public override async Task RemoveByPrefixAsync(string prefix, params object[] prefixParameters) { prefix = PrepareKeyPrefix(prefix, prefixParameters); var db = await _connectionWrapper.GetDatabaseAsync(); var instanceName = _appSettings.Get().InstanceName ?? string.Empty; foreach (var endPoint in await _connectionWrapper.GetEndPointsAsync()) { var keys = await GetKeysAsync(endPoint, instanceName + prefix); db.KeyDelete(keys.ToArray()); } RemoveByPrefixInstanceData(prefix); } /// /// Clear all cache data /// /// A task that represents the asynchronous operation public override async Task ClearAsync() { await _connectionWrapper.FlushDatabaseAsync(); ClearInstanceData(); } #endregion }