C#使用Redis第三方库存储时需要注意两个问题

通过C#第三方库向Redis存储数据遇到的几个问题

https://github.com/ServiceStack/ServiceStack.Redis

1、将对象转json字符串

JsonObject jsonObject=new JsonObject();
jsonObject.Add("aa","年后");
jsonObject.Add("bb","12132");
string str=jsonObject.ToJson(); 
RedisCacheHelper.Add<object>("test", str, DateTime.Now.AddDays(1));
var v= RedisCacheHelper.Get<object>("test");

不仅多了一个反斜杠,中文还被编码,如果写之前加上UrlEncode,读出时候使用UrlDecode则正常显示。

例如:

string str =" [\"aaa\",\"bbb\"]";
str= System.Web.HttpUtility.UrlEncode(str);
RedisCacheHelper.Add<string>("aa",str,new TimeSpan(1,0,0,0));
string strRet= RedisCacheHelper.Get<string>("aa");
strRet= System.Web.HttpUtility.UrlDecode(strRet);

2、直接使用对象

可以用以下方法,直接传对象 

List<string> list=new List<string>();
list.Add("adfa");
list.Add("bbb");
RedisCacheHelper.Add<object>("test", list, DateTime.Now.AddDays(1)
List < string > list1= RedisCacheHelper.Get<List<string>>("test");//默认传出来的是JArray

3、推荐一个好用的Redis工具

https://github.com/uglide/RedisDesktopManager

猜你喜欢

转载自www.cnblogs.com/zhaogaojian/p/10251862.html