hybridcache是什么
在 .net 9 中,microsoft 将 hybridcache 带入了框架体系。
hybridcache 是一种新的缓存模型,设计用于封装本地缓存和分布式缓存,使用者无需担心选择缓存类型,从而优化性能和维护效率。
实际上,hybridcache 基于 idistributedcache 提供的接口和操作,但增加了一些其他的特性,如封装两类不同缓存库(本地和分布),支持标签删除(tag-based cache eviction)和约束选项。
需要注意的是,hybridcache仍处于preview阶段。
hybridcache 与 idistributedcache 的区别
idistributedcache:
- 仅支持分布式缓存,如 redis、sql server、memorycache。
- 选择依赖于目标缓存和管理设备。
- 不支持标签删除,只能基于键值操作。
hybridcache:
- 支持封装本地和分布式缓存,在读取时优先读取本地缓存,如本地不存在,再读取分布式。
- 支持标签删除,通过指定标签管理缓存内容。
- 选项更加精简,支持自动化操作和选项约束。
hybridcache 的好处
- 性能优化: 本地缓存速度超过分布式,使用 hybridcache 可以减少读取分布缓存库时的延迟。
- 精简化工程: 使用者不需再自行核实选择哪个缓存,增加了工程效率。
- 标签管理: 缓存标签记录不同类型数据,便于分类管理和删除缓存。
- 安全性: 支持选项约束,使缓存操作更严格,防止错误使用和内容亏失。
代码示例
以下代码展示如何使用 hybridcache:
1. 添加缓存服务
var builder = webapplication.createbuilder(args); // 注册 hybridcache 服务 builder.services.addhybridcache(); // 注册 redis 缓存服务,为 hybridcache 提供分布式缓存 builder.services.addstackexchangerediscache(options => { options.configuration = builder.configuration.getconnectionstring("redisconnectionstring"); }); builder.services.addcontrollers();
2. 实现接口操作
读取缓存
[httpget("getcache")] public async task<string[]> get() { return await _cache.getorcreateasync( "a-1", async cancel => await task.fromresult(summaries) ); }
删除缓存
[httpget("deletecache")] public async task<bool> delete() { await _cache.removeasync("a-1"); return true; }
通过标签读取缓存
[httpget("getcachebytag")] public async task<string[]> getcachebytag() { var tags = new list<string> { "tag1", "tag2", "tag3" }; var entryoptions = new hybridcacheentryoptions { expiration = timespan.fromminutes(1), localcacheexpiration = timespan.fromminutes(1) }; return await _cache.getorcreateasync( "a-1", async cancel => await task.fromresult(summaries), entryoptions, tags ); }
通过标签删除缓存
[httpget("deletecachebytag")] public async task<bool> deletecachebytag() { var tags = new list<string> { "tag1" }; await _cache.removebytagasync(tags); return true; }
小结
.net 9 的 hybridcache 提供了一种便捷且高效的缓存解决方案,将本地缓存和分布式缓存无缝结合,为开发者简化了缓存逻辑,同时提供了更多高级功能,如标签管理和选项约束。通过代码示例可以看出,hybridcache 的操作直观且易于实现,非常适合现代应用场景。
如果你正在使用 .net 9,尝试将 hybridcache 应用于你的项目中,体验其高效与简洁!
文章转载自:chester·chen
原文链接:https://www.cnblogs.com/chenyishi/p/18626831
体验地址:引迈 - jnpf快速开发平台_低代码开发平台_零代码开发平台_流程设计器_表单引擎_工作流引擎_软件架构
到此这篇关于.net 9 中的 多级缓存 hybridcache的文章就介绍到这了,更多相关.net 多级缓存 hybridcache内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论