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 {
|
public static class DistributedCacheExtensions {
|
||||||
//TODO: named caches, CacheService?
|
//TODO: named caches, CacheService?
|
||||||
//TODO: thread-safe locks to prevent fetching data more than once
|
//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) {
|
public static async Task<T?> Get<T>(this IDistributedCache cache, string key) {
|
||||||
var buffer = await cache.GetAsync(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);
|
var stream = new MemoryStream(buffer);
|
||||||
|
try {
|
||||||
var data = await JsonSerializer.DeserializeAsync<T>(stream);
|
var data = await JsonSerializer.DeserializeAsync<T>(stream);
|
||||||
|
|
||||||
return data != null ? (T)data : default;
|
return data != null ? (T)data : default;
|
||||||
}
|
}
|
||||||
|
catch {
|
||||||
|
return default;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public static async Task<T> Fetch<T>(this IDistributedCache cache, string key, TimeSpan ttl,
|
public static async Task<T> Fetch<T>(this IDistributedCache cache, string key, TimeSpan ttl,
|
||||||
Func<Task<T>> fetcher) {
|
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) {
|
public static async Task Set<T>(this IDistributedCache cache, string key, T data, TimeSpan ttl) {
|
||||||
using var ms = new MemoryStream();
|
using var stream = new MemoryStream();
|
||||||
await JsonSerializer.SerializeAsync(ms, data);
|
await JsonSerializer.SerializeAsync(stream, data);
|
||||||
var buffer = new Memory<byte>();
|
stream.Position = 0;
|
||||||
_ = await ms.ReadAsync(buffer);
|
|
||||||
var options = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = ttl };
|
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