c# 如何利用redis存储对象,并实现快速查询
在 C# 中使用 Redis 存储对象并实现快速查询,可以通过以下步骤实现。示例中使用 StackExchange.Redis 库和 JSON 序列化,结合 Redis 的哈希(Hash)和有序集合(Sorted Set)优化查询。
1. 安装依赖库
# 安装 Redis 客户端库 Install-Package StackExchange.Redis # 安装 JSON 序列化库(System.Text.Json 或 Newtonsoft.Json) Install-Package System.Text.Json
2. 定义数据模型
假设存储一个 User 对象:
public class User
{
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}
3. 存储对象到 Redis
方案 1:使用字符串类型(String)存储 JSON
using StackExchange.Redis;
using System.Text.Json;
public class RedisService
{
private readonly ConnectionMultiplexer _redis;
private readonly IDatabase _db;
public RedisService(str
