我正在使用ServiceStack.Redis库来使用Redis。首先,我实施了this解决方案。 get / set方法适用于纯文本/字符串。
现在,当我保存带引号的字符串(使用转义字符)时,它会正确保存(我在redis-cli中验证相同)。但Get方法返回删除了所有双引号的字符串。
例如,保存此字符串 - “TestSample”已保存并按预期获得。另外,使用\“\”引号\“”保存“TestSample”很好,并且在redis-cli中显示相同。但Get方法的输出变为“带引号的TestSample”
public bool SetDataInCache<T>(string cacheKey, T cacheData)
{
try
{
using (_redisClient = new RedisClient(_cacheConfigs.RedisHost))
{
_redisClient.As<T>().SetValue(cacheKey, cacheData, new TimeSpan(0,0,300));
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public T GetDataFromCacheByType<T>(string cacheKey)
{
T retVal = default(T);
try
{
using (_redisClient = new RedisClient(_cacheConfigs.RedisHost))
{
if (_redisClient.ContainsKey(cacheKey))
{
var wrapper = _redisClient.As<T>();
retVal = wrapper.GetValue(cacheKey);
}
return retVal;
}
}
catch (Exception ex)
{
return retVal;
}
用法:
cacheObj.SetDataInCache("MyKey1","TestSample");
cacheObj.SetDataInCache("MyKey2","TestSample \"with\" \"quotes\"");
string result1 = Convert.ToString(cacheObj.GetDataFromCacheByType<string>("MyKey1"));
string result2 = Convert.ToString(cacheObj.GetDataFromCacheByType<string>("MyKey2"));
实际:“带引号的测试样本”
预期:“TestSample”带\“\”引号\“”
Typed Generic API仅用于创建用于序列化复杂类型的通用Redis客户端。如果您要实现通用缓存,则应使用IRedisClient
API,例如:
_redisClient.Set(cacheKey, cacheData, new TimeSpan(0,0,300));
然后检索回:
var retVal = _redisClient.Get<T>(cacheKey);
或者,为了保存字符串,或者如果您想自己序列化POCO,可以使用IRedisClient
SetValue / GetValue字符串API,例如:
_redisClient.SetValue(cacheKey, cacheData.ToJson());
var retVal = _redisClient.GetValue(cacheKey).FromJson<T>();
注意:调用
IRedisClient.ContainsKey()
执行额外的不必要的Redis I / O操作,因为无论如何你都要返回default(T)
,你应该调用_redisClient.Get<T>()
,它返回非现有键的默认值。