ServiceStack Redis Get<T>(key)移除字符串引号问题求助
解决ServiceStack.Redis存储带转义引号字符串丢失引号的问题
我来帮你搞定这个问题!你遇到的情况其实是ServiceStack.Redis的JSON序列化机制在搞鬼,咱们一步步分析解决:
问题根源
当你用_redisClient.As<T>().SetValue()和GetValue()处理字符串类型时,ServiceStack.Redis默认会把字符串当作JSON值来序列化/反序列化:
- 存储时:你的输入字符串
"TestSample \"with\" \"quotes\""会被序列化成JSON格式的内容,最终Redis里存的是带外层双引号的字符串:"TestSample \"with\" \"quotes\"" - 读取时:JSON反序列化会自动解析转义字符,把
\"转换成普通的",所以你拿到的结果就变成了TestSample with quotes,丢失了原有的转义。
而redis-cli显示正常是因为它直接展示Redis里的原始存储内容,不会做JSON解析。
解决方案
改用RedisClient的原生字符串操作方法,跳过JSON序列化,直接读写原始字符串。这里给你修改后的代码:
修改后的Set方法
public bool SetDataInCache<T>(string cacheKey, T cacheData) { try { using (var redisClient = new RedisClient(_cacheConfigs.RedisHost)) { if (typeof(T) == typeof(string)) { // 字符串类型直接用原生SetString,不做JSON序列化 redisClient.SetString(cacheKey, cacheData as string, new TimeSpan(0, 0, 300)); } else { // 非字符串类型保留原有的泛型序列化逻辑 redisClient.As<T>().SetValue(cacheKey, cacheData, new TimeSpan(0, 0, 300)); } } return true; } catch (Exception ex) { return false; } }
修改后的Get方法
public T GetDataFromCacheByType<T>(string cacheKey) { try { using (var redisClient = new RedisClient(_cacheConfigs.RedisHost)) { if (redisClient.ContainsKey(cacheKey)) { if (typeof(T) == typeof(string)) { // 原生GetString获取原始字符串,不做JSON反序列化 var strValue = redisClient.GetString(cacheKey); return (T)(object)strValue; } else { var wrapper = redisClient.As<T>(); return wrapper.GetValue(cacheKey); } } return default(T); } } catch (Exception ex) { return default(T); } }
验证效果
现在再运行你的测试代码:
cacheObj.SetDataInCache("MyKey2","TestSample \"with\" \"quotes\""); string result2 = cacheObj.GetDataFromCacheByType<string>("MyKey2");
result2会正确返回TestSample \"with\" \"quotes\",和你预期的一致!
如果你大部分缓存操作都是字符串,也可以单独封装SetStringCache和GetStringCache方法,这样代码会更清晰~
内容的提问来源于stack exchange,提问作者Arjun_TECH
相关产品推荐
相关产品推荐

