Redis for .NET Developer – Connecting with C#

来源:互联网 时间:1970-01-01

In the second blog post series “ Redis for .NET Developer ” I will show how we will use C# to connect to Redis.

We will be using StackExchange.Redis library to connect to Redis. One can download StackExchange. Redis through NuGet.

StackExchange.Redis is a high performance general purpose redis client for .NET languages (C# etc).

1. Let’s Download our Nuget package, one can use the command line like below or use Visual Studio (I am using VS2015).

PM> Install-Package StackExchange.Redis.StrongName PM>Install-PackageStackExchange.Redis.StrongName

Search for redis in your nuget window.

Nuget Redis

Once installed you will see in your output windows.

Nuget Redis Result

Now that the nuget package is installed, we can build a C# console app that will connect to your redis server.Below is a sample code to connect to localhost of your redis.


ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");IDatabase db = redis.GetDatabase();if(db.StringSet("testKey", "testValue")){ var val = db.StringGet("testKey"); Console.WriteLine(val);} ConnectionMultiplexer redis=ConnectionMultiplexer.Connect("localhost"); IDatabase db=redis.GetDatabase(); if(db.StringSet("testKey","testValue")){ varval=db.StringGet("testKey"); Console.WriteLine(val);}

The above code will allow you to connect to Redis and store a string key “testKey” with a value of “testValue”.

For better modulation of Redis it is recommended to store ConnectionMultiplexer as a static singleton in your application.

Below is example of a RedisStore that stores the ConnectionMultiplexer as a static Lazy loaded singleton.


public class RedisStore{ private static readonly Lazy<ConnectionMultiplexer> LazyConnection; static RedisStore() { var configurationOptions = new ConfigurationOptions { EndPoints = { "localhost" } }; LazyConnection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(configurationOptions)); } public static ConnectionMultiplexer Connection => LazyConnection.Value; public static IDatabase RedisCache => Connection.GetDatabase();} publicclassRedisStore{ privatestaticreadonlyLazy<ConnectionMultiplexer>LazyConnection;staticRedisStore(){varconfigurationOptions=newConfigurationOptions{EndPoints={"localhost"}};LazyConnection=newLazy<ConnectionMultiplexer>(()=>ConnectionMultiplexer.Connect(configurationOptions));}publicstaticConnectionMultiplexerConnection=>LazyConnection.Value;publicstaticIDatabaseRedisCache=>Connection.GetDatabase();}

Now our previous code would something like


var redis = RedisStore.RedisCache; if(redis.StringSet("testKey", "testValue")){ var val = redis.StringGet("testKey"); Console.WriteLine(val);} varredis=RedisStore.RedisCache; if(redis.StringSet("testKey","testValue")){ varval=redis.StringGet("testKey"); Console.WriteLine(val);}

In my next blog post I will cover the data structures that Redis provides.