redisjson 使用C# NReJSON 实现对redisjson的 使用
redisjson 听说性能比mongo快几十倍,但是,一直没有找到这样的教程。
现在我就做一个示例。
redisjson服务是用docker搭建的。
可以参考这篇文章
来搭建服务。
以下是代码示例
需要安装Nuget包
Install-Package NReJSON -Version 4.0.0
//创建redis对象 var db = ConnectionMultiplexer.Connect("127.0.0.1").GetDatabase(); var key = "test"; string json = JsonConvert.SerializeObject(new UserInfo() { Age = 19, Name = "张三", Time = DateTime.Now, Address = new Address() { Name = "北京" } }, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-dd HH:mm:ss" }); OperationResult result = await db.JsonSetAsync(key, json); if (result.IsSuccess) { Console.WriteLine("json保存成功!"); } RedisResult result2 = await db.JsonGetAsync(key, "."); if (!result2.IsNull) { Console.WriteLine($"获取成功:{result2}"); } OperationResult result3 = await db.JsonSetAsync(key, JsonConvert.SerializeObject("成都"), ".Address.Name"); OperationResult result4 = await db.JsonSetAsync(key, JsonConvert.SerializeObject("王五"), ".Name"); if (result3.IsSuccess && result4.IsSuccess) { Console.WriteLine("json修改成功!"); } RedisResult result5 = await db.JsonGetAsync(key, ".Name", ".Age", ".Time", ".Address.Name"); if (!result5.IsNull) { Console.WriteLine($"获取成功:{result5}"); } Console.WriteLine("redis json 测试!"); Console.ReadLine();
public class UserInfo { /// <summary> /// 姓名 /// </summary> public string Name { get; set; } /// <summary> /// 年龄 /// </summary> public int Age { get; set; } /// <summary> /// 时间 /// </summary> public DateTime Time { get; set; } /// <summary> /// 地址 /// </summary> public Address Address { get; set; } } /// <summary> /// 地址 /// </summary> public class Address { public string Name { get; set; } }
代码还是很完整的,有助于了解实际情况。
第一步保存的结果
第二步,修改结果
控制台结果: