Fix cache serializer
This commit is contained in:
parent
3e4410f52c
commit
f7539b5374
1 changed files with 13 additions and 9 deletions
|
@ -6,16 +6,21 @@ namespace Iceshrimp.Backend.Core.Extensions;
|
|||
public static class DistributedCacheExtensions {
|
||||
//TODO: named caches, CacheService?
|
||||
//TODO: thread-safe locks to prevent fetching data more than once
|
||||
//TODO: sliding window ttl?
|
||||
|
||||
public static async Task<T?> Get<T>(this IDistributedCache cache, string key) {
|
||||
var buffer = await cache.GetAsync(key);
|
||||
if (buffer == null) return default;
|
||||
if (buffer == null || buffer.Length == 0) return default;
|
||||
|
||||
var stream = new MemoryStream(buffer);
|
||||
try {
|
||||
var data = await JsonSerializer.DeserializeAsync<T>(stream);
|
||||
|
||||
return data != null ? (T)data : default;
|
||||
}
|
||||
catch {
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<T> Fetch<T>(this IDistributedCache cache, string key, TimeSpan ttl,
|
||||
Func<Task<T>> fetcher) {
|
||||
|
@ -28,11 +33,10 @@ public static class DistributedCacheExtensions {
|
|||
}
|
||||
|
||||
public static async Task Set<T>(this IDistributedCache cache, string key, T data, TimeSpan ttl) {
|
||||
using var ms = new MemoryStream();
|
||||
await JsonSerializer.SerializeAsync(ms, data);
|
||||
var buffer = new Memory<byte>();
|
||||
_ = await ms.ReadAsync(buffer);
|
||||
using var stream = new MemoryStream();
|
||||
await JsonSerializer.SerializeAsync(stream, data);
|
||||
stream.Position = 0;
|
||||
var options = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = ttl };
|
||||
await cache.SetAsync(key, buffer.ToArray(), options);
|
||||
await cache.SetAsync(key, stream.ToArray(), options);
|
||||
}
|
||||
}
|
Loading…
Add table
Reference in a new issue