connect to redis in csharp

To connect to Redis in C#, you can use the StackExchange.Redis library which is a high performance general purpose .NET Redis client that is built on top of the native Redis protocol. Here is a sample code that connects to Redis server, sets a value and retrieves it:

main.cs
using StackExchange.Redis;

// Creating a Redis connection
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");

// Get an instance of the Redis database
IDatabase db = redis.GetDatabase();

// Set a value
db.StringSet("mykey", "Hello World");

// Retrieve a value
string value = db.StringGet("mykey");
Console.WriteLine(value); // Output: Hello World

// Dispose the Redis connection
redis.Dispose();
423 chars
18 lines

This code first creates a Redis connection using ConnectionMultiplexer.Connect() method. Then, it gets an instance of the Redis database using redis.GetDatabase() method. It sets a value using db.StringSet() method and retrieves it using db.StringGet() method.

Don't forget to dispose the Redis connection by calling redis.Dispose() method when you are done using it.

gistlibby LogSnag