Thursday 10 September 2015

ServiceStack.Redis C# client demo

This article shows some simple code to communicate with Redis.io , using ServiceStack.Redis. The easiest way to install ServiceStack.Redis client is to use the Nuget Package Manager GUI inside Visual Studio, as there are several packages. The following packages are required:


<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="ServiceStack.Common" version="4.0.44" targetFramework="net45" />
  <package id="ServiceStack.Interfaces" version="4.0.44" targetFramework="net45" />
  <package id="ServiceStack.Redis" version="4.0.44" targetFramework="net45" />
  <package id="ServiceStack.Text" version="4.0.44" targetFramework="net45" />
</packages>



The easiest way to install is to use Manage Nuget Packages and search for "redis" and choose "C# Redis client for the Redis NoSQL DB", as displayed above. After adding the Redis client Nuget library, make sure you have access to a Redis server. On Windows, it is possible to install Redis server by downloading it from the GitHub page supported by MSOpenTech. Note that Redis server is officially supported on Linux and in production environments, Redis is considered a bit experimental for Windows servers. However, Redis is now an established technology. It is though suggested to download not the very newest version of the Redis package and server, version 2.6 should work well as of now (p.t. 10.09.2015). Download the Redis client and server from here: Redis 64 Windows binaries (zipped) Installing Redis is dead simple, just unzip and copy Redis binaries to a folder. However, for production environments, you will want to install Redis as a Windows Service. This is explained here: Running Redis as a Windows Service Here is some sample code that communicates with the Redis server (considered to be available on localhost, default port is 6379):

using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RedisTesting
{
    class Program
    {

        static void Main(string[] args)
        {

            RedisTypedClientDemo();

            RedisClientDemo();

            NativeClientDemo();

            TransactionDemo();

            PublishDemo();

            SubscribeDemo();

            Console.WriteLine("Press the ENTER key to exit.");
            Console.ReadLine(); 

        }

        private static void SubscribeDemo()
        {
            using (IRedisClient client = new RedisClient())
            {
                var sub = client.CreateSubscription();
                sub.OnMessage = (c, m) => Console.WriteLine("Got message {0} from channel {1}", m, c);
                sub.SubscribeToChannels("news");
            }
        }

        private static void PublishDemo()
        {
            using (IRedisClient client = new RedisClient())
            {
                client.PublishMessage("debug", "Hello C#");
            }
        }

        private static void TransactionDemo()
        {
            using (IRedisClient client = new RedisClient())
            {
                var transaction = client.CreateTransaction();
                transaction.QueueCommand(c => c.Set("abc", 1));
                transaction.QueueCommand(c => c.Increment("abc", 1));
                transaction.Commit();
                var result = client.Get<int>("abc");
                Console.WriteLine(result);
            }
        }

        private static void RedisTypedClientDemo()
        {
            long lastId = 0;

            using (IRedisClient client = new RedisClient())
            {
                var customerClient = client.As<Customer>();
                var customer = new Customer
                {
                    Id = customerClient.GetNextSequence(),
                    Adress = "123 Main Street",
                    Name = "Bob Green",
                    Orders = new List<Order>
                    {
                        new Order { OrderNumber = "AB123" },
                        new Order { OrderNumber = "AB124" }
                    }
                };

                var storedCustomer = customerClient.Store(customer);
                lastId = storedCustomer.Id;

            }

            using (IRedisClient client = new RedisClient())
            {
                var customerClient = client.As<Customer>();
                var customer = client.GetById<Customer>(lastId);
                Console.WriteLine("Get customer {0}, with name {1}", customer.Id, customer.Name);
            }
        }

        private static void RedisClientDemo()
        {
            using (IRedisClient client = new RedisClient())
            {
                var customerNames = client.Lists["urn:customernames"];
                customerNames.Clear();
                customerNames.Add("Joe");
                customerNames.Add("Mary");
                customerNames.Add("Bob");
            }

            using (IRedisClient client = new RedisClient())
            {
                var customerNames = client.Lists["urn:customernames"];

                foreach (var customerName in customerNames)
                {
                    Console.WriteLine("Customer: " + customerName);
                }
            }
        }

        private static void NativeClientDemo()
        {
            using (IRedisNativeClient client = new RedisClient("localhost", 6379))
            {
                client.Set("urn:messages:1", Encoding.UTF8.GetBytes("Hello C# World"));
            }

            using (IRedisNativeClient client = new RedisClient("localhost", 6379))
            {
                var result = Encoding.UTF8.GetString(client.Get("urn:messages:1"));
                Console.WriteLine("Message:" + result);
            }
        }
    }
}

//Class Customer

using System.Collections.Generic;

namespace RedisTesting
{
    
    public class Customer
    {

        public long Id { get; set; }

        public string Name { get; set; }

        public string Adress { get; set; }

        public List<Order> Orders { get; set; }

    }


}



//Class Order 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RedisTesting
{
    
    public class Order
    {

        public string OrderNumber { get; set; }

    }

}



Share this article on LinkedIn.

2 comments: