分布式缓存已成为提高 .NET 应用程序性能和可伸缩性的一种流行方式。 这就是为什么开发人员在分布式缓存中缓存越来越多的数据。 然而,随之而来的是一些挑战。 一项重要的挑战是确保缓存中的数据始终与数据库同步。 这是因为缓存保留了数据库中已经存在的数据的副本。
如果您有多个应用程序更新数据库中的相同数据,但并非所有应用程序都可以访问分布式缓存,那么您最终会遇到缓存中的数据比数据库中的数据更旧且不同的情况。 而且,虽然这对于某些参考类型的数据可能是可以的,但对于事务性数据绝对是不可接受的。 参考数据是您经常阅读但不经常修改的数据(例如产品目录),而交易数据是您经常阅读和修改的数据(例如客户或帐户数据)。
NCache 更多信息 缓存依赖文档 NCache 配套文档
您如何确保分布式缓存与数据库保持同步?
答案是: SqlCacheDependency
. 它是 ASP.NET 缓存 (System.Web.Caching) 的一部分,允许您使用 SQL 语句在数据库中指定数据集,然后在数据库中修改数据集时从 SQL Server 2005/2008 接收 .NET 事件通知.
NCache 已在内部成立 SqlCacheDependency
为目的 与 SQL Server 2005/2008 或 Oracle 数据库同步缓存. 给你, NCache 提供了一个名为 SqlDependency 的类似接口,它允许您指定一个 SQL 语句,该语句表示给定表中的一个或多个行,这些行构成您的缓存项。 NCache 然后在内部使用 SqlCacheDependency
针对这些行建立与数据库的链接。
因此,如果您的某个应用程序在数据库中更新了您的数据,SQL Server 会触发一个 .NET 事件通知,该通知 NCache 从分布式缓存中捕获并删除相应的项目。 这解决了具有相同数据的两个不同副本的数据不一致问题。 这是因为当您的应用程序下次想要相同的数据时,它在缓存中找不到它,并被迫从数据库中检索最新的副本,然后它也会缓存该副本。 这边走, NCache 确保缓存中的数据始终与数据库中的数据一致。
下面是一个使用SqlDependency的源码示例 NCache 内部使用 SqlCacheDependency
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
public class Program { // A standard Load method that loads a single row from database public Customer LoadCustomer(Customer cust) { String key = "Customer:CustomerID:" + cust.CustomerID; Customer cust2 = (Customer)NCache.Cache.Get(key); if (cust2 != null) return cust2; CustomerFactory custFactory = new CustomerFactory(); // Load a single customer from the database // SELECT * FROM Customers WHERE CustomerID = 'ALFKI' custFactory.Load(cust); // Create a SqlCacheDependency for this item CacheItem item = new CacheItem(cust); item.Dependency = SqlDependencyFactory(connectionString, "SELECT CustomerID FROM Customers WHERE CustomerID = '" + cust.CustomerID + "'"); // Store item in the cache along with SqlCacheDependency NCache.Cache.Insert(key, item); return cust; } // A query method public List<Customer> FindCustomers(String city) { String key = "List<Customer>:City:" + city; List<Customer> custList = (List<Customer>)NCache.Cache.Get(key); if (custList != null) return custList; CustomerFactory custFactory = new CustomerFactory(); // Load a list of customers from database based on a criteria // SELECT * FROM Customers WHERE City = 'San Francisco' custList = custFactory.FindByCity(city); // Create a SqlCacheDependency for this list of customers CacheItem item = new CacheItem(custList); item.Dependency = SqlDependencyFactory.(connectionString, "SELECT CustomerID FROM Customers WHERE City = '" + city + "'"); // Store list of customers in the cache along with SqlCacheDependency NCache.Cache.Insert (key, item); return custList; } } |
缓存对 SQL 的依赖 Oracle 数据库缓存依赖关系 自定义缓存依赖
综上所述,SqlDependency 特性的 NCache 允许您将缓存与数据库同步并保持数据完整性。 您现在可以开始缓存所有数据,而不必担心使用缓存中的陈旧数据。 当然,您缓存的数据越多,您的应用程序性能和可扩展性就越好。
因此,请下载完整的 60 天试用版 NCache Enterprise 并亲自尝试一下。