缓存序列化对象
存储和读取复杂对象。
缓存序列化对象 是 CoddyKit 上的免费 C# Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C# Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C# Academy 课程共包含 4 节课。
缓存不止字符串
实际应用缓存的是对象,而不只是字符串。由于 IDistributedCache 存储字节,您必须先将对象序列化为字节或字符串表示形式,读取时再进行反序列化。JSON 通常是首选格式。
使用 System.Text.Json 进行序列化
使用 System.Text.Json 将对象转换为 JSON 字符串,然后使用 SetStringAsync 存储。
using System.Text.Json;
var product = new Product { Id = 1, Name = "Coffee", Price = 4.5m };
string json = JsonSerializer.Serialize(product);
await _cache.SetStringAsync("product:1", json);读取时进行反序列化
读取时,获取 JSON 字符串并将其反序列化回相应类型,同时记得处理缓存未命中的 null。
string json = await _cache.GetStringAsync("product:1");
if (json is null) return null;
Product product = JsonSerializer.Deserialize<Product>(json);可复用的泛型辅助方法
将序列化和反序列化逻辑封装到扩展方法中,使调用方能够简洁地缓存任意类型。
public static async Task SetAsync<T>(
this IDistributedCache cache, string key, T value,
DistributedCacheEntryOptions options)
{
string json = JsonSerializer.Serialize(value);
await cache.SetStringAsync(key, json, options);
}泛型获取辅助方法
对应的获取方法会将内容反序列化回 T,未命中时返回 default。
public static async Task<T> GetAsync<T>(
this IDistributedCache cache, string key)
{
string json = await cache.GetStringAsync(key);
return json is null ? default : JsonSerializer.Deserialize<T>(json);
}GetOrCreate 模式
将旁路缓存与序列化组合到一个辅助方法中:返回缓存的对象;如果对象不存在,则运行工厂方法,缓存其结果并返回。
public static async Task<T> GetOrCreateAsync<T>(
this IDistributedCache cache, string key,
Func<Task<T>> factory, DistributedCacheEntryOptions options)
{
var existing = await cache.GetAsync<T>(key);
if (existing is not null) return existing;
var created = await factory();
await cache.SetAsync(key, created, options);
return created;
}使用 GetOrCreate
调用处只需一行代码,就能隐藏所有缓存机制。
var product = await _cache.GetOrCreateAsync(
"product:1",
() => _repository.LoadProductAsync(1),
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(15)
});序列化程序选项
请复用同一个 JsonSerializerOptions 实例(例如使用 camelCase、忽略空值),以保持缓存负载的一致性并缩小其大小,同时避免反复分配 options。
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition =
System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
};缓存结构的版本管理
如果缓存类型的结构发生变化,旧 JSON 可能无法反序列化。请在键中加入版本片段(如 product:v2:1),这样部署后会自然跳过不兼容的条目。
保持负载精简
只缓存您需要的字段。较小的负载意味着 Redis 中更少的网络和内存使用,并且每次读取和写入时都能更快地完成序列化。
注意序列化开销
序列化并非没有开销。对于访问非常频繁的路径,可以考虑紧凑格式或缓存预先生成的结果,并始终通过测量确认缓存总体上确实带来了收益。
快速检查
测试序列化对象的缓存。
总结
要缓存对象,请在写入时将其序列化(通常通过 System.Text.Json 使用 JSON),在读取时再进行反序列化。通用的 SetAsync<T>/GetAsync<T> 和 GetOrCreateAsync 辅助方法隐藏了具体机制,并简洁地实现了旁路缓存。请复用 JsonSerializerOptions,在结构变化时为缓存键添加版本号,保持负载精简,并测量访问频繁路径上的序列化开销。
常见问题解答
「缓存序列化对象」课时是免费的吗?
是的 — 「缓存序列化对象」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C# Academy 课程的其余内容,请升级到 CoddyKit PRO。 C# Academy 课程共包含 4 节课。
「缓存序列化对象」这节课中我会学到什么?
存储和读取复杂对象。 你通过在浏览器中直接运行的动手代码来练习 C# Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 C# Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 C# Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「缓存序列化对象」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 C# Academy 课中编写并运行代码吗?
能。每节 C# Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。