Simple In-Memory Caching in .Net with Apache Ignite
In the Last Post we have seen how to setup Apache Ignite Server as an independent process . Now we will see how to use the Apache Ignite as an In-Memory Cache in .NET. We will see through an example how to write Clients which knows how to talk with the Apache Ignite Server.
Installing Necessary Nuget Packages
Before starting off we have to install Apache.Ignite NuGet package to the Console Application that we have created which is required to enable Apache Ignite functionality. This can be installed through Visual studio "Manage NuGet Packages" tool.
Once the NuGet package is installed for the project we have to write clients which can access the Apache Ignite cache store to "Put" and "Get" data. Basically Apache Ignite will store the data as Key Value Pair. Code to access the cache from the client is shown below:
Code
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 | using Apache.Ignite.Core; using Apache.Ignite.Core.Client; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InMemeoryCache { internal class Program { static void Main(string[] args) { var cfg = new IgniteClientConfiguration { Endpoints = new[] { "127.0.0.1:10800"} }; using (var client = Ignition.StartClient(cfg)) { var cache = client.GetOrCreateCache<int, string>("MyCache"); if(cache.ContainsKey(1)) { Console.WriteLine($"Cache Contains {cache.Get(1)}"); } else { cache.Put(1, "One"); Console.WriteLine($"Inserting into Cache"); } } Console.ReadKey(); } } } |
Once the Server is successfully started we can run the client application. If we run the client application for the first time we can see that the cache will be empty and the else case will be executed where we will put the data in the cache. Output will be as shown below:
Once client execution completes we have already pushed the data into Ignite. Then if we execute the client once again we can see that the if condition will be true and the data is retrieved from the cache. Output will be as shown below:
Comments
Post a Comment