学习

Redis OM 库支持从 Redis 中声明式存储和检索对象。在没有 Redis Stack的情况下,这将仅限于在 Redis 中使用哈希和 ID 查找对象。您仍然可以使用 Document 属性来装饰您想要存储在 Redis 中的类。从那里,您只需要在 RedisCollection 上调用 Insert 或 InsertAsync ,或在 RedisConnection 上调用 Set 或 SetAsync ,并将您想要设置在 Redis 中的对象传递给它。然后,您可以使用 Get<T> 或 GetAsync<T> 与 RedisConnection 一起检索这些对象,或者使用 FindById 或 FindByIdAsync 在 RedisCollection 中检索这些对象。

public class Program
{
    [Document(Prefixes = new []{"Employee"})]
    public class Employee
    {
        [RedisIdField]
        public string Id{ get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

        public double Sales { get; set; }

        public string Department { get; set; }
    }

    static async Task Main(string[] args)
    {
        var provider = new RedisConnectionProvider("redis://localhost:6379");
        var connection = provider.Connection;
        var employees = provider.RedisCollection<Employee>();
        var employee1 = new Employee{Name="Bob", Age=32, Sales = 100000, Department="Partner Sales"};
        var employee2 = new Employee{Name="Alice", Age=45, Sales = 200000, Department="EMEA Sales"};
        var idp1 = await connection.SetAsync(employee1);
        var idp2 = await employees.InsertAsync(employee2);

        var reconstitutedE1 = await connection.GetAsync<Employee>(idp1);
        var reconstitutedE2 = await employees.FindByIdAsync(idp2);
        Console.WriteLine($"First Employee's name is {reconstitutedE1.Name}, they are {reconstitutedE1.Age} years old, " +
                          $"they work in the {reconstitutedE1.Department} department and have sold {reconstitutedE1.Sales}, " +
                          $"their ID is: {reconstitutedE1.Id}");
        Console.WriteLine($"Second Employee's name is {reconstitutedE2.Name}, they are {reconstitutedE2.Age} years old, " +
                        $"they work in the {reconstitutedE2.Department} department and have sold {reconstitutedE2.Sales}, " +
                        $"their ID is: {reconstitutedE2.Id}");
    }
}

上面的代码将声明一个 Employee 类,并允许您将员工添加到 Redis 中,然后从 Redis 中检索员工,此方法的输出将如下所示:

First Employee's name is Bob, they are 32 years old, they work in the Partner Sales department and have sold 100000, their ID is: 01FHDFE115DKRWZW0XNF17V2RK
Second Employee's name is Alice, they are 45 years old, they work in the EMEA Sales department and have sold 200000, their ID is: 01FHDFE11T23K6FCJQNHVEF92F

如果您想直接在 Redis 中找到它们,您可以运行 HGETALL Employee:01FHDFE115DKRWZW0XNF17V2RK ,这将从 Redis 中检索员工对象作为哈希。如果您没有指定前缀,则前缀将是完全限定的类名。