fix: if cache get bytes then skip serealize

This commit is contained in:
Polianin Nikita 2024-06-21 21:44:34 +03:00
parent 79151e7da8
commit 1a0d539e76
2 changed files with 5 additions and 4 deletions

View File

@ -17,7 +17,7 @@ public class DistributedCacheService(IDistributedCache cache) : ICacheService
SlidingExpiration = slidingExpiration SlidingExpiration = slidingExpiration
}; };
var serializedValue = JsonSerializer.SerializeToUtf8Bytes(value); var serializedValue = value as byte[] ?? JsonSerializer.SerializeToUtf8Bytes(value);
await cache.SetAsync(key, serializedValue, options, cancellationToken); await cache.SetAsync(key, serializedValue, options, cancellationToken);
} }

View File

@ -1,6 +1,7 @@
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
using Mirea.Api.Security.Common.Interfaces; using Mirea.Api.Security.Common.Interfaces;
using System; using System;
using System.Text.Json;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -16,14 +17,14 @@ public class MemoryCacheService(IMemoryCache cache) : ICacheService
SlidingExpiration = slidingExpiration SlidingExpiration = slidingExpiration
}; };
cache.Set(key, value, options); cache.Set(key, value as byte[] ?? JsonSerializer.SerializeToUtf8Bytes(value), options);
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default) public Task<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default)
{ {
cache.TryGetValue(key, out T? value); cache.TryGetValue(key, out byte[]? value);
return Task.FromResult(value); return Task.FromResult(JsonSerializer.Deserialize<T>(value));
} }
public Task RemoveAsync(string key, CancellationToken cancellationToken = default) public Task RemoveAsync(string key, CancellationToken cancellationToken = default)