Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Cache value allows null #400

Merged
merged 3 commits into from
Jan 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ namespace Masa.BuildingBlocks.Caching;

public class CacheEntry<T> : CacheEntryOptions<T>
{
public T Value { get; }
public T? Value { get; }

public CacheEntry(T value)
public CacheEntry(T? value)
{
Value = value;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,31 @@ public class CombinedCacheEntry<T>
{
public CacheEntryOptions? MemoryCacheEntryOptions { get; set; }

public Func<CacheEntry<T>> DistributedCacheEntryFunc { get; set; }
public Func<CacheEntry<T>>? DistributedCacheEntryFunc { get; set; }

/// <summary>
/// Only async methods are supported
/// </summary>
public Func<Task<CacheEntry<T>>>? DistributedCacheEntryAsyncFunc { get; set; }

public CombinedCacheEntry()
{
}

private CombinedCacheEntry(CacheEntryOptions? memoryCacheEntryOptions) : this()
{
MemoryCacheEntryOptions = memoryCacheEntryOptions;
}

public CombinedCacheEntry(Func<CacheEntry<T>> distributedCacheEntryFunc, CacheEntryOptions? memoryCacheEntryOptions)
: this(memoryCacheEntryOptions)
{
DistributedCacheEntryFunc = distributedCacheEntryFunc;
}

public CombinedCacheEntry(Func<Task<CacheEntry<T>>> distributedCacheEntryAsyncFunc, CacheEntryOptions? memoryCacheEntryOptions)
: this(memoryCacheEntryOptions)
{
DistributedCacheEntryAsyncFunc = distributedCacheEntryAsyncFunc;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ public abstract class DistributedCacheClientBase : CacheClientBase, IDistributed

public abstract T? GetOrSet<T>(string key, Func<CacheEntry<T>> setter, Action<CacheOptions>? action = null);

public abstract Task<T?> GetOrSetAsync<T>(string key, Func<CacheEntry<T>> setter, Action<CacheOptions>? action = null);
public virtual Task<T?> GetOrSetAsync<T>(string key, Func<CacheEntry<T>> setter, Action<CacheOptions>? action = null)
=> GetOrSetAsync(key, () => Task.FromResult(setter.Invoke()), action);

public abstract Task<T?> GetOrSetAsync<T>(string key, Func<Task<CacheEntry<T>>> setter, Action<CacheOptions>? action = null);

public abstract void Refresh(params string[] keys);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ public interface IDistributedCacheClient : ICacheClient

Task<T?> GetOrSetAsync<T>(string key, Func<CacheEntry<T>> setter, Action<CacheOptions>? action = null);

Task<T?> GetOrSetAsync<T>(string key, Func<Task<CacheEntry<T>>> setter, Action<CacheOptions>? action = null);

/// <summary>
/// Flush cache time to live
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,21 @@ public interface IMultilevelCacheClient : ICacheClient
CacheEntryOptions? memoryCacheEntryOptions = null,
Action<CacheOptions>? action = null);

/// <summary>
/// Get cache, set cache if cache does not exist
/// </summary>
/// <param name="key">Cache key</param>
/// <param name="distributedCacheEntryFunc">Distributed cache information returned when the memory cache does not exist</param>
/// <param name="memoryCacheEntryOptions">Memory cache lifetime configuration,which is consistent with the default configuration when it is empty</param>
/// <param name="action">Cache configuration, used to change the global cache configuration information</param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
Task<T?> GetOrSetAsync<T>(
string key,
Func<Task<CacheEntry<T>>> distributedCacheEntryFunc,
CacheEntryOptions? memoryCacheEntryOptions = null,
Action<CacheOptions>? action = null);

Task<T?> GetOrSetAsync<T>(string key, CombinedCacheEntry<T> combinedCacheEntry, Action<CacheOptions>? action = null);

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,13 @@ public abstract class MultilevelCacheClientBase : CacheClientBase, IMultilevelCa
Func<CacheEntry<T>> distributedCacheEntryFunc,
CacheEntryOptions? memoryCacheEntryOptions = null,
Action<CacheOptions>? action = null)
=> GetOrSetAsync(key, new CombinedCacheEntry<T>()
{
DistributedCacheEntryFunc = distributedCacheEntryFunc,
MemoryCacheEntryOptions = memoryCacheEntryOptions
}, action);
=> GetOrSetAsync(key, new CombinedCacheEntry<T>(distributedCacheEntryFunc, memoryCacheEntryOptions), action);

public virtual Task<T?> GetOrSetAsync<T>(string key,
Func<Task<CacheEntry<T>>> distributedCacheEntryFunc,
CacheEntryOptions? memoryCacheEntryOptions = null,
Action<CacheOptions>? action = null)
=> GetOrSetAsync(key, new CombinedCacheEntry<T>(distributedCacheEntryFunc, memoryCacheEntryOptions), action);

public abstract Task<T?> GetOrSetAsync<T>(string key, CombinedCacheEntry<T> combinedCacheEntry, Action<CacheOptions>? action = null);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,17 @@ public RedisCacheClient(RedisConfigurationOptions redisConfigurationOptions,
return GetAndRefresh(key, () =>
{
var cacheEntry = setter();
if (cacheEntry.Value == null)
return default;

SetCore(key, cacheEntry.Value, cacheEntry);
return cacheEntry.Value;
});
}

public override async Task<T?> GetOrSetAsync<T>(
string key,
Func<CacheEntry<T>> setter,
Func<Task<CacheEntry<T>>> setter,
Action<CacheOptions>? action = null)
where T : default
{
Expand All @@ -109,7 +112,10 @@ public RedisCacheClient(RedisConfigurationOptions redisConfigurationOptions,
key = FormatCacheKey<T>(key, action);
return await GetAndRefreshAsync(key, async () =>
{
var cacheEntry = setter();
var cacheEntry = await setter();
if (cacheEntry.Value == null)
return default;

await SetCoreAsync(key, cacheEntry.Value, cacheEntry).ConfigureAwait(false);
return cacheEntry.Value;
}).ConfigureAwait(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -365,14 +365,18 @@ public async Task TestGetListAsync(params string[] keys)
[DataTestMethod]
[DataRow("test_1", "123")]
[DataRow("test_2", "")]
public void TestGetOrSet(string key, string value)
[DataRow("test_2", null)]
public void TestGetOrSet(string key, string? value)
{
var res = _distributedCacheClient.GetOrSet(key, () =>
{
if (value == null)
return new CacheEntry<string?>(null);

if (string.IsNullOrWhiteSpace(value))
return new CacheEntry<string>("", TimeSpan.FromSeconds(30));
return new CacheEntry<string?>("", TimeSpan.FromSeconds(30));

return new CacheEntry<string>(value, TimeSpan.FromHours(1));
return new CacheEntry<string?>(value, TimeSpan.FromHours(1));
});

Assert.AreEqual(value, res);
Expand All @@ -382,14 +386,18 @@ public void TestGetOrSet(string key, string value)
[DataTestMethod]
[DataRow("test_1", "123")]
[DataRow("test_2", "")]
public async Task TestGetOrSetAsync(string key, string value)
[DataRow("test_2", null)]
public async Task TestGetOrSetAsync(string key, string? value)
{
var res = await _distributedCacheClient.GetOrSetAsync(key, () =>
{
if (value == null)
return Task.FromResult(new CacheEntry<string?>(null));

if (string.IsNullOrWhiteSpace(value))
return new CacheEntry<string>("", TimeSpan.FromSeconds(30));
return Task.FromResult(new CacheEntry<string?>("", TimeSpan.FromSeconds(30)));

return new CacheEntry<string>(value, TimeSpan.FromHours(1));
return Task.FromResult(new CacheEntry<string?>(value, TimeSpan.FromHours(1)));
});

Assert.AreEqual(value, res);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,36 @@ public void TestGetOrSet()
{
DistributedCacheEntryFunc = () => new CacheEntry<Guid>(guid, TimeSpan.FromSeconds(3))
}));

Assert.AreEqual(null, _multilevelCacheClient.GetOrSet("test105", new CombinedCacheEntry<decimal?>()
{
DistributedCacheEntryFunc = () => new CacheEntry<decimal?>(null)
}));
_multilevelCacheClient.Remove<string>("test100");
_multilevelCacheClient.Remove<decimal?>("test101");
_multilevelCacheClient.Remove<decimal>("test102");
_multilevelCacheClient.Remove<Guid?>("test103");
_multilevelCacheClient.Remove<Guid?>("test104");
_multilevelCacheClient.Remove<Guid?>("test105");
}

[TestMethod]
public void TestGetOrSet2()
{
Assert.ThrowsException<NotSupportedException>(() =>
{
_multilevelCacheClient.GetOrSet("test100", new CombinedCacheEntry<string>()
{
DistributedCacheEntryAsyncFunc = () => Task.FromResult(new CacheEntry<string>("success"))
});
});

Assert.ThrowsException<NotSupportedException>(() =>
{
_multilevelCacheClient.GetOrSet("test100", new CombinedCacheEntry<string>());
});

_multilevelCacheClient.Remove<string>("test100");
}

[TestMethod]
Expand All @@ -158,9 +183,32 @@ public async Task TestGetOrSetAsync()
DistributedCacheEntryFunc = () => new CacheEntry<Guid?>(guid, TimeSpan.FromSeconds(3))
}));

Assert.AreEqual(null, await _multilevelCacheClient.GetOrSetAsync("test103", new CombinedCacheEntry<Guid?>()
{
DistributedCacheEntryFunc = () => new CacheEntry<Guid?>(null, TimeSpan.FromSeconds(3))
}));

Assert.AreEqual(null, await _multilevelCacheClient.GetOrSetAsync("test104", new CombinedCacheEntry<Guid?>()
{
DistributedCacheEntryAsyncFunc = () => Task.FromResult(new CacheEntry<Guid?>(null, TimeSpan.FromSeconds(3)))
}));

await _multilevelCacheClient.RemoveAsync<string>("test100");
await _multilevelCacheClient.RemoveAsync<decimal?>("test101");
await _multilevelCacheClient.RemoveAsync<Guid?>("test102");
await _multilevelCacheClient.RemoveAsync<Guid?>("test103");
await _multilevelCacheClient.RemoveAsync<Guid?>("test104");
}

[TestMethod]
public async Task TestGetOrSet2Async()
{
await Assert.ThrowsExceptionAsync<NotSupportedException>(async () =>
{
await _multilevelCacheClient.GetOrSetAsync("test100", new CombinedCacheEntry<string?>());
});

await _multilevelCacheClient.RemoveAsync<string>("test100");
}

[TestMethod]
Expand Down Expand Up @@ -535,10 +583,10 @@ public void TestFormatCacheKeys()
var data = ((MultilevelCacheClient)_multilevelCacheClient).FormatCacheKeys<string>(list, CacheKeyType.TypeName);
Assert.AreEqual(2, data.Count);

Assert.AreEqual("Multilevel1",data[0].Key);
Assert.AreEqual("String.Multilevel1",data[0].FormattedKey);
Assert.AreEqual("Multilevel2",data[1].Key);
Assert.AreEqual("String.Multilevel2",data[1].FormattedKey);
Assert.AreEqual("Multilevel1", data[0].Key);
Assert.AreEqual("String.Multilevel1", data[0].FormattedKey);
Assert.AreEqual("Multilevel2", data[1].Key);
Assert.AreEqual("String.Multilevel2", data[1].FormattedKey);
}
}
#pragma warning restore CS0618
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,9 @@ public MultilevelCacheClient(IMemoryCache memoryCache,
Action<T?>? valueChanged,
Action<MultilevelCacheOptions>? action = null) where T : default
=> GetCoreAsync(key, valueChanged, action,
(formattedKey, cacheOptionsAction) =>
Task.FromResult(_distributedCacheClient.Get<T>(formattedKey, cacheOptionsAction))).ConfigureAwait(false).GetAwaiter().GetResult();
(formattedKey, cacheOptionsAction) =>
Task.FromResult(_distributedCacheClient.Get<T>(formattedKey, cacheOptionsAction))).ConfigureAwait(false).GetAwaiter()
.GetResult();

public override Task<T?> GetCoreAsync<T>(string key, Action<T?>? valueChanged, Action<MultilevelCacheOptions>? action = null)
where T : default
Expand Down Expand Up @@ -133,8 +134,10 @@ public MultilevelCacheClient(IMemoryCache memoryCache,
IEnumerable<string> keys,
Action<MultilevelCacheOptions>? action = null) where T : default
=> GetListCoreAsync<T>(keys, action,
(formattedKeys, cacheOptionsAction) =>
Task.FromResult(_distributedCacheClient.GetList<T>(formattedKeys, cacheOptionsAction))).ConfigureAwait(false).GetAwaiter().GetResult();
(formattedKeys, cacheOptionsAction) =>
Task.FromResult(_distributedCacheClient.GetList<T>(formattedKeys, cacheOptionsAction))).ConfigureAwait(false)
.GetAwaiter()
.GetResult();

public override Task<IEnumerable<T?>> GetListAsync<T>(
IEnumerable<string> keys,
Expand All @@ -154,7 +157,8 @@ public MultilevelCacheClient(IMemoryCache memoryCache,

var awaitValues = new List<T?>();
if (awaitCacheKeyItems.Any())
awaitValues = (await func.Invoke(awaitCacheKeyItems.Select(x => x.FormattedKey), CacheOptionsAction).ConfigureAwait(false)).ToList();
awaitValues = (await func.Invoke(awaitCacheKeyItems.Select(x => x.FormattedKey), CacheOptionsAction).ConfigureAwait(false))
.ToList();

return FillData(list, awaitCacheKeyItems, awaitValues, GetMemoryCacheEntryOptions(multilevelCacheOptions));
}
Expand All @@ -171,7 +175,19 @@ public MultilevelCacheClient(IMemoryCache memoryCache,

if (!_memoryCache.TryGetValue(formattedKey, out T? value))
{
value = _distributedCacheClient.GetOrSet(formattedKey, combinedCacheEntry.DistributedCacheEntryFunc, CacheOptionsAction);
CacheEntry<T> cacheEntry = default!;
if (combinedCacheEntry.DistributedCacheEntryFunc != null)
{
value = _distributedCacheClient.GetOrSet(
formattedKey,
() =>
{
cacheEntry = combinedCacheEntry.DistributedCacheEntryFunc.Invoke();
return cacheEntry;
},
CacheOptionsAction);
}
else throw new NotSupportedException();

SetCore(new SetOptions<T>()
{
Expand All @@ -180,7 +196,7 @@ public MultilevelCacheClient(IMemoryCache memoryCache,
MemoryCacheEntryOptions = combinedCacheEntry.MemoryCacheEntryOptions
});

PubSub(key, formattedKey, SubscribeOperation.Set, value, combinedCacheEntry.DistributedCacheEntryFunc.Invoke());
PubSub(key, formattedKey, SubscribeOperation.Set, value, cacheEntry);
}

return value;
Expand All @@ -200,10 +216,30 @@ public MultilevelCacheClient(IMemoryCache memoryCache,

if (!_memoryCache.TryGetValue(formattedKey, out T? value))
{
value = await _distributedCacheClient.GetOrSetAsync(
formattedKey,
combinedCacheEntry.DistributedCacheEntryFunc,
CacheOptionsAction).ConfigureAwait(false);
CacheEntry<T> cacheEntry = default!;
if (combinedCacheEntry.DistributedCacheEntryAsyncFunc != null)
{
value = await _distributedCacheClient.GetOrSetAsync(
formattedKey,
async () =>
{
cacheEntry = await combinedCacheEntry.DistributedCacheEntryAsyncFunc.Invoke();
return cacheEntry;
},
CacheOptionsAction).ConfigureAwait(false);
}
else if (combinedCacheEntry.DistributedCacheEntryFunc != null)
{
value = await _distributedCacheClient.GetOrSetAsync(
formattedKey,
() =>
{
cacheEntry = combinedCacheEntry.DistributedCacheEntryFunc.Invoke();
return cacheEntry;
},
CacheOptionsAction).ConfigureAwait(false);
}
else throw new NotSupportedException();

SetCore(new SetOptions<T>()
{
Expand All @@ -212,7 +248,8 @@ public MultilevelCacheClient(IMemoryCache memoryCache,
MemoryCacheEntryOptions = combinedCacheEntry.MemoryCacheEntryOptions
});

await PubSubAsync(key, formattedKey, SubscribeOperation.Set, value, combinedCacheEntry.DistributedCacheEntryFunc.Invoke()).ConfigureAwait(false);
await PubSubAsync(key, formattedKey, SubscribeOperation.Set, value, cacheEntry)
.ConfigureAwait(false);
}

return value;
Expand Down Expand Up @@ -248,7 +285,8 @@ public override async Task SetAsync<T>(string key, T value, CombinedCacheEntryOp
var multilevelCacheOptions = GetMultilevelCacheOptions(action);
var formattedKey = FormatCacheKey<T>(key, GetCacheKeyType(multilevelCacheOptions));

await _distributedCacheClient.SetAsync(formattedKey, value, options?.DistributedCacheEntryOptions, CacheOptionsAction).ConfigureAwait(false);
await _distributedCacheClient.SetAsync(formattedKey, value, options?.DistributedCacheEntryOptions, CacheOptionsAction)
.ConfigureAwait(false);

SetCore(new SetOptions<T>()
{
Expand Down