Getting started with Redis

This is a guide for getting started with Redis on .NET. First download and unzip Redis windows binaries from GitHubhttps://github.com/MSOpenTech/redis/releases

If we want to run Redis as a service on Windows, we need to install it. Open command prompt (with administrative rights) and navigate into folder where Redis was unzipped. Type following command to install Redis:
redis-server --service-install redis.windows.conf --loglevel verbose
Command basically says that we want to install redis server which uses redis.windows.conf as its config file and loglevel is verbose. Now we have Redis listed in services. Go and start it.

Now database is on and we are ready to write some code. Open Visual Studio and create a new console project. Then right click project file and select "Manage Nuget packages..."

Select "Online" from left and type "StackExchange" into search field. Install StackExchange.Redis.

Next type Json into search field and install Json.NET.

Then let's start using Redis database by writing and running a simple piece of code:

        static void Main(string[] args)
        {
            // This should be stored and reused
            var redis = ConnectionMultiplexer.Connect("localhost");

            // IDatabase is simple object which is cheap to build
            IDatabase db = redis.GetDatabase(2);

            // Store string data into database
            db.StringSet("ExamplePrimaryKey", "AndExampleValue");
        }

Our example software connects to localhost database, gets database number 2 (there are 13 databases available in Redis) and stores "AndExampleValue" into key called "ExamplePrimaryKey".

Ok, that seems quite simple. Lets see what we have in our database now. Open command prompt again (or reuse old), navigate into redis folder and type "redis-cli". Now we have connected into our local database with Redis console. Next we should select our database by typing command "Select 2". Then get string data by typing "GET ExamplePrimaryKey". If everything went OK, you should see a string "AndExampleValue".

We can expand our code by adding following lines after db.StringSet(...):
// Retrieve value from database and print it into console
Console.WriteLine(db.StringGet("ExamplePrimaryKey"));
           
Console.ReadKey();
Now when we run our software we should see "AndExampleValue" on console. Now if we look what is in our database by typing "GET ExamplePrimaryKey" again in Redis console, we will see only one value. That's because Redis has replaced old value with new one because we used same key.

Now let's do something more complex. Lets add a new class called "ExampleClass" into our program.
public class ExampleClass
{
    public string ExampleValue { get; set; }
    public List<string> ExampleList { get; set; }
}
Then change program main to this:
        static void Main(string[] args)
        {
            // This should be stored and reused
            var redis = ConnectionMultiplexer.Connect("localhost");
            // IDatabase is simple object which is cheap to build
            IDatabase db = redis.GetDatabase(2);
            // Create instance and set some values
            var exampleInstance = new ExampleClass();
            exampleInstance.ExampleList = new List<string>();
            exampleInstance.ExampleValue = "Something";
            exampleInstance.ExampleList.Add("First item");
            exampleInstance.ExampleList.Add("Second item");
            exampleInstance.ExampleList.Add("Third item");
            // Fetch unique id from database for this object
            var uniqId = db.StringIncrement("ExampleClassUniqueId");
            // Store it into database as JsonObject
            db.StringSet("ExampleClass:" + uniqId, JsonConvert.SerializeObject(exampleInstance));
            // Retrieve stored object from database
            var readObject = JsonConvert.DeserializeObject<ExampleClass>(db.StringGet("ExampleClass:" + uniqId));
            Console.WriteLine("Value: " + readObject.ExampleValue + " Items in list: " + readObject.ExampleList.Count());
           
            Console.ReadKey();
        }
Run program few times. Then open Redis console again and type "KEYS *" into it. As you can see from example picture (and from your console), we are having multiple values in our database with different keys.


Lets look what ExampleClass:1 contains. Type "GET ExampleClass:1" into console. You should see values which were entered for exampleInstance in our program.

That's a simple guide for using Redis from .NET. In next post we will dive into sets and hashes which are quite common datatypes in Redis database.

The best way to predict the future is to implement it.

7 kommenttia:

  1. Great blog. All posts have something to learn. Your work is very good and i appreciate you and hoping for some more informative posts.keep writing
    Web development Company in India Company | Web development Company Bangalore
    Web Development Company in Bangalore | Responsive Web development

    VastaaPoista
  2. As a website design company .Web India Market offer a full-circle approach in responsive website designing and web development services. Our website designing services covers Strategic Planning, Business Intelligence, Creative Application Development, Digital Marketing, SEO services and e-commerce solutions.

    VastaaPoista
  3. Thank you for sharing this info. it will be helpful for our Database Development Services.
    Database Development Services
    Database Development

    VastaaPoista
  4. Web Design Sydney: It is a great sharing...I am very much pleased with the contents you have mentioned. I wanted to thank you for this great article. .Logo Design Sydney,Logo Design in Coimbatore,Brochure Design in Coimbatore

    VastaaPoista