These days, many businesses require the processing power to deal with high numbers of transactional and reference data during peak times. For instance, banks processing customer transactions during holidays. However, a big challenge is to process this data without hampering your application’s performance. Generally, application tiers are linearly scalable, but databases are not. High transactional loads can result in a database bottleneck and overwhelm your system. This bottleneck can be resolved by introducing an in-memory distributed caching to .NET application for faster data access.
An in-memory distributed cache spans multiple servers but works as a single cache instance and is transparent to the applications that use it. It reduces the load from back-end servers & databases as any active or transient data is served from the cache.
NCache Details Dynamic Clustering Distributed Caching
NCache is an open-source, in-memory distributed cache for both .NET and Java-based applications. NCache helps achieve fast transactional speeds and data consistency as new servers are added to this cache cluster to meet your growing performance needs.
The following figure illustrates this architecture:
Cached data is equally distributed between all servers and even replicates to avoid data loss and ensure high availability. Therefore, the distributed cache handles hundreds of thousands of requests per second, preventing downtime during peak loads.
This distributed structure ensures no single point of failure as if even one cache server is down, it receives data from the other server nodes. Hence, your business is not affected and can easily add more servers to the distributed cache if needed.
The ideal data for caching includes read-intensive frequently but occasionally changed to achieve maximum performance of distributed caches. Distributed caches store the data as key-value pairs, thus making it simple to use and access.
NCache Details Dynamic Clustering Caching Topologies
Using NCache as a Distributed Cache
Along with a dramatic performance boost to your .NET applications, distributed caches such as NCache provide multiple advanced features that make cache usage even more flexible to cater to different use cases and business needs – including the ones below.
NCache CRUD operations
You can easily incorporate a distributed cache in your .NET application by connecting to the cache and creating a key against your cache item fetched from the database. You can then insert the item into the cache with an expiration of 30 minutes and fetch it using this connection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Specify the cache name to connect with it ICache cache = CacheManager.GetCache("demoCache"); // Get product from database var product = FetchProductFromDB(1001); // Generate a key for the cache item string key = "Product:1001"; // Create cache item and add 30sec sliding expiration var cacheItem = new CacheItem(product); cacheItem.Expiration = new Expiration(ExpirationType.Sliding, TimeSpan.FromMinutes(30)); // Now add this item in cache for future use cache.Insert(key, cacheItem); // Fetch item from cache product = cache.Get(key); |
NCache Details Sliding Expiration NCache
Sync Cache with Database
There might be a case where the cached data in the database is changed. This situation raises an integrity issue rendering your cached data stale while your application is unaware of it. To solve this problem, NCache can auto-synchronize your cache with the database. Consequently, whenever any change occurs in the database for a cached record, it will be removed automatically from the cache to ensure data freshness..
To further assist with this mechanism, NCache supports Write-Through, Loader & Refresher, and Persistence store that keeps the data in the cache synchronized with the database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Get orders against customerID from DB var order = FetchOrderByCustomerID("ALFKI"); // Generate unique cache key for the order string key = $"Order:{order.OrderID}"; CacheItem item = new CacheItem(order); // Create SQL query to select the data from database string query = "SELECT CustomerID, Address, City FROM dbo.Customers WHERE CustomerID = 'ALFKI';"; //Specify database connection string and the query to create and set SQLCacheDependency. item.Dependency = new SqlCacheDependency(dbConnString, query); // Insert the item into the cache cache.Insert(key, item); |
NCache Details DB Synchronization Cache Data Dependency
SQL Queries
NCache supports an SQL querying mechanism to let you search your cache according to a given criterion and returns the required result set. NCache uses a query language that is very close to the native SQL structured language, which makes querying indexed cached data easier. It provides ADO.NET-compliant APIs like ExecuteReader, ExecuteScalar, and ExecuteNonQuery to search (SELECT) and remove (DELETE) data from the cache.
NCache Details SQL and LINQ Support in NCache SQL Query
ExecuteReader is used to search data and return key-value pairs. While using the ExecuteReader method, you can specify whether you want only the keys to be returned, or keys and their data (either as a whole or in chunks).
1 2 3 4 5 6 7 8 9 10 11 |
//string query = "SELECT * FROM FQN.Product WHERE UnitsInStock > ?"; var queryCommand = new QueryCommand(query); queryCommand.Parameters.Add("UnitsInStock",0); ICacheReader reader = cache.ExecuteReader(queryCommand); while (reader.Read()) { string ID = reader.GetValue("ProductID"); string Name = reader.GetValue("ProductName"); } |
LINQ Queries
LINQ is a generic .NET query language that allows you to search and filter out data from your data source. LINQ syntax is quite similar to SQL, but in functionalities, it provides you with better and more optimised querying methods when querying your NCache servers. It provides the ability to allow more efficient query expressions while catering to syntax checking during code compilation.
NCache seamlessly integrates LINQ to query information within the cache via a LINQ provider. The link provider facilitates the execution of LINQ queries over the distributed cache while improving the application’s performance without changing the LINQ object model.
Query expressions query and transform data from your LINQ-enabled distributed cache servers.
1 2 3 4 |
IQueryable products = new NCacheQuery(cache); IQueryable product = from prod in products where prod.UnitsInStock > 10 select prod; |
NCache Details LINQ for Distributed Caching IQueryable
Concluding Thoughts
Other than providing performance and scalability, NCache provides other useful features too. And yet, it hides its implementation-related complexity and gives a straightforward way to use it. If you are looking for a .NET-based distributed cache, without compromising performance and scalability, look no further than NCache. It is a pure .NET platform with all the bells and whistles of modern distributed caching