Redis Data Types
Redis supports a variety of data types, allowing you to store and retrieve different types of values.
Strings
Strings are the simplest data type in Redis. They can contain any binary data, such as text, JSON, or serialized objects. Strings are commonly used for key-value storage and retrieval.
Here's an example of using strings in Redis with C#:
1const string player = "Kobe Bryant";
2
3// Set the string value
4db.StringSet("favorite_player", player);
5
6// Get the string value
7string favoritePlayer = db.StringGet("favorite_player");
8Console.WriteLine("My favorite player is " + favoritePlayer);
Lists
Lists in Redis are ordered collections of strings, allowing you to add elements to the head or tail of the list. They are useful for implementing queues, stacks, and maintaining an ordered collection of data.
Here's an example of using lists in Redis with C#:
1// Push elements to the list
2db.ListRightPush("queue", "item1");
3db.ListRightPush("queue", "item2");
4
5// Get all elements of the list
6RedisValue[] queue = db.ListRange("queue");
7Console.WriteLine("Queue: " + string.Join(", ", queue));
Hashes
Hashes in Redis are maps between string fields and string values, like a dictionary. They are useful for representing objects, where each field is a property of the object.
Here's an example of using hashes in Redis with C#:
1// Set hash field values
2db.HashSet("user", new[] { new HashEntry("name", "John"), new HashEntry("age", "30") });
3
4// Get hash field values
5RedisValue name = db.HashGet("user", "name");
6RedisValue age = db.HashGet("user", "age");
7Console.WriteLine("User: Name = " + name + ", Age = " + age);
xxxxxxxxxx
}
using StackExchange.Redis;
using System;
class Program
{
static void Main()
{
// Connect to Redis
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost:6379");
IDatabase db = redis.GetDatabase();
// Set a string value
db.StringSet("name", "John");
// Get the string value
string name = db.StringGet("name");
Console.WriteLine("Name: " + name);
// Set a list value
db.ListRightPush("users", "user1");
db.ListRightPush("users", "user2");
// Get the list value
RedisValue[] users = db.ListRange("users");
Console.WriteLine("Users: " + string.Join(", ", users));
// Set a hash value
db.HashSet("person", new[] { new HashEntry("name", "John"), new HashEntry("age", "30") });