Created
July 27, 2025 15:29
-
-
Save emonarafat/b6c5fa0738013b56064881e6b1bed180 to your computer and use it in GitHub Desktop.
π‘ Optimized JSON serialization, compression, and caching strategy in .NET APIs using System.Text.Json + Redis for high-throughput, scalable performance.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Text.Json; | |
| using System.IO.Compression; | |
| using StackExchange.Redis; | |
| using System.Text; | |
| public static class JsonCacheHelper | |
| { | |
| private static readonly JsonSerializerOptions _jsonOptions = new() | |
| { | |
| PropertyNamingPolicy = JsonNamingPolicy.CamelCase, | |
| WriteIndented = false | |
| }; | |
| public static async Task SetCompressedAsync<T>(IDatabase redis, string key, T obj, TimeSpan? expiry = null) | |
| { | |
| var json = JsonSerializer.Serialize(obj, _jsonOptions); | |
| var compressed = Compress(json); | |
| await redis.StringSetAsync(key, compressed, expiry); | |
| } | |
| public static async Task<T?> GetCompressedAsync<T>(IDatabase redis, string key) | |
| { | |
| var compressed = await redis.StringGetAsync(key); | |
| if (compressed.IsNullOrEmpty) | |
| return default; | |
| var json = Decompress(compressed); | |
| return JsonSerializer.Deserialize<T>(json, _jsonOptions); | |
| } | |
| private static byte[] Compress(string json) | |
| { | |
| var bytes = Encoding.UTF8.GetBytes(json); | |
| using var output = new MemoryStream(); | |
| using (var gzip = new GZipStream(output, CompressionMode.Compress)) | |
| { | |
| gzip.Write(bytes, 0, bytes.Length); | |
| } | |
| return output.ToArray(); | |
| } | |
| private static string Decompress(byte[] compressed) | |
| { | |
| using var input = new MemoryStream(compressed); | |
| using var gzip = new GZipStream(input, CompressionMode.Decompress); | |
| using var reader = new StreamReader(gzip); | |
| return reader.ReadToEnd(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment