NCache 是一个用于 Entity Framework Core (EF Core) 的分布式内存缓存提供程序,它通过缓存查询结果来消除数据库瓶颈。然而,它也存在一些局限性;高事务性的 EF Core 应用程序可能会因为过多的数据库查询而在数据库层遇到性能问题。应用程序层可以水平扩展,但数据库层却是一个瓶颈。
NCache100% 原生 .NET 分布式缓存,通过缓存频繁访问的数据和卸载数据库查询来增强 EF Core 应用程序。这提高了性能和可扩展性并减少了数据库的总体负载。
NCache 扩展 英孚核心 使用 C# 扩展方法,允许无缝缓存而无需修改现有逻辑。
交易数据包括频繁变化的记录,例如客户详细信息、订单和交易。短期缓存这些频繁访问的数据可以减少数据库查询、加快响应时间并最大限度地减少争用。
方法: 从缓存(), 从缓存异步()
从缓存(): 如果可用,则从缓存中检索查询结果;否则,从数据库中获取并将结果存储在缓存中以供将来使用。 从缓存() 支持 Group By、Order By Ascending、Order By Descending、Sum、Min、Max、Average、Count、Contains、Like 和 FirstOrDefault 函数。
var resultSet = (from cust in context.Customers
where cust.CustomerId == someCustomerId
select cust).FromCache(options).ToList();
参考数据包括相对静态的数据集,例如产品目录和查找值。长期缓存这些数据可以消除冗余的数据库查询,从而提高应用程序的速度。
方法: 加载到缓存(), 加载缓存异步()
加载缓存(): 将整个数据集加载到缓存中,确保后续查询直接从缓存而不是数据库中检索数据。
var resultSet = (from custOrder in context.Orders
where custOrder.Customer.CustomerId == someCustomerId
select custOrder).LoadIntoCache(out string cacheKey, options);
直接从缓存中检索参考数据可让应用程序避免数据库查询,从而缩短响应时间。但是,必须将整个数据集预加载到缓存中,以确保结果准确并避免查询响应不完整。 (直接从缓存中检索数据,无需数据库调用).
方法: 仅从缓存(), FromCacheOnlyAsync()
从CacheOnly()开始: 查询结果仅从缓存中检索,不查询数据库,从而确保对预加载数据集进行超快速查找。但是,为了确保此方法有效,您需要确保缓存整个数据集以保持查询的准确性。
var resultSet = (from cust in context.Customers
where cust.CustomerId == someCustomerId
select cust).FromCacheOnly();
NCache 提供直接 API,用于高效管理缓存实体,而无需完全依赖 EF Core 扩展方法。借助其缓存 API,开发人员可以以编程方式在缓存中插入、更新和删除对象,从而能够精细控制缓存行为,同时优化高性能应用程序的数据检索。
直接在缓存中插入、删除和更新实体。
ICache cache = CacheManager.GetCache(cacheName);
// Inserting an entity into cache
cache.Insert(customerKey, cacheItem);
延迟查询执行允许应用程序执行聚合函数,例如 数数(), 总和()和 平均() 直接对缓存数据进行操作,无需重复查询数据库。此功能通过在内存缓存中直接执行诸如计数和求和之类的聚合操作,消除了将大型数据集传输到客户端的网络开销。这减少了冗余查询,提高了性能,并加快了高事务环境下的数据检索速度。
using (var context = new NorthwindContext())
{
var resultSet = context.Products
.Where(p => p.UnitPrice == 10)
.GroupBy(p => p.ProductName)
.Select(group => group.Key)
.FromCache(out cacheKey, options)
.ToList();
}
NCache 允许应用程序直接对缓存数据执行 LINQ 查询,从而无需重复进行数据库查询。通过利用内存处理,此方法显著提升了查询性能并降低了数据库负载。您可以直接对缓存数据运行 LINQ 查询,而无需访问数据库。
using (var context = new NorthwindContext())
{
var result = context.Customers
.Where(b => (b.CompanyName.Contains("Alfreds Futterkist")))
.FromCacheOnly()
}
NCache 提供缓存选项,允许开发人员根据应用程序需求自定义缓存行为。这样可以更好地控制数据存储、设置过期策略、启用 SQL 依赖项跟踪以实现自动失效,以及定义如何将数据存储在缓存中以实现高效检索。
var options = new CachingOptions
{
QueryIdentifier = "CustomerEntity",
CreateDbDependency = true,
StoreAs = StoreAs.SeperateEntities,
Priority = Runtime.CacheItemPriority.High
};
options.SetAbsoluteExpiration(DateTime.Now.AddSeconds(20));
NCache 包含内置日志记录和监控功能,可跟踪缓存使用情况、衡量性能指标并实时检测潜在问题。它与 Microsoft.Extensions.Logging 无缝集成,使开发人员能够分析缓存行为、排查问题并高效优化性能。
Install-Package EntityFrameworkCore.NCache
public partial class NorthwindContext : DbContext
{
...
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Parameters specified in App.config
string cacheId = ConfigurationManager.AppSettings["CacheId"];
string connString = ConfigurationManager.AppSettings["ConnString"];
bool errorEnabled = bool.Parse(ConfigurationManager.AppSettings["ErrorEnabled"]);
int bulkInsertChunkSize = Int32.Parse(ConfigurationManager.AppSettings["BulkInsertChunkSize"]);
// Configure cache with connection retries and security
var options = new CacheConnectionOptions();
options.RetryInterval = TimeSpan.FromSeconds(3);
options.ConnectionRetries = 2;
options.ServerList = new List<ServerInfo>()
{
new ServerInfo("20.200.20.XX", 9800)
};
// Configure cache with security
options.UserCredentials = new Credentials("john_smith", "12345");
NCacheConfiguration.Configure(cacheId, DependencyType.SqlServer, options, errorEnabled, bulkInsertChunkSize);
optionsBuilder.UseSqlServer(connString);
}
}