Redis Get Value
- Underlying API:
IDatabase.StringGet(key), reads string‑type data from Redis, returnsRedisValue RedisValue.HasValue:Check whether the key exists and contains valid datatrue:Key exists;false:Key does not exist
- After fetching binary data, you need to deserialize it to restore the original object
- Returns
default(T)when key is missing- Value types(int/DateTime):returns 0, minimum datetime
- Reference types(class):returns null
Examples
using StackExchange.Redis;
using Newtonsoft.Json;
using System.Text;
/// <summary>
/// Read cached object by Key
/// </summary>
/// <typeparam name="T">Target object type</typeparam>
/// <param name="key">Cache key name</param>
/// <returns>Returns object if exists; returns default(T) if not exists</returns>
public T Get<T>(string key)
{
// Read data from redis
RedisValue rValue = db.StringGet(key);
// Judge key not exists
if (!rValue.HasValue)
{
return default(T);
}
// Deserialize binary data to entity
T result = Deserialize<T>(rValue);
return result;
}
/// <summary>
/// Deserialize:byte[] → T object
/// </summary>
private T Deserialize<T>(byte[] serializedObject)
{
if (serializedObject == null)
{
return default(T);
}
// Convert byte array to json string
string json = Encoding.UTF8.GetString(serializedObject);
// Convert json to target entity
return JsonConvert.DeserializeObject<T>(json);
}
/// <summary>
/// Object serialization method (paired with Set)
/// </summary>
private byte[] Serialize(object data)
{
string json = JsonConvert.SerializeObject(data);
return Encoding.UTF8.GetBytes(json);
}Code language: C# (cs)
Notes
- Implicit type conversion
RedisValuesupports direct implicit conversion to byte[], you can passrValuedirectly intoDeserialize<T>(byte[]), compiler handles conversion automatically. - Paired read‑write workflow
Set write flow:Entity → Serialize → byte[] → Redis
Get read flow:Redis → byte[] → Deserialize → EntityCode language: CSS (css)
- Calling example
// Example1: Read custom entity
var user = Get<User>("user_1001");
// Example2: Read simple string
string text = Get<string>("msg");
// Example3: Read numeric value
int count = Get<int>("visit_count");Code language: C# (cs)
- Mismatched serialize‑deserialize types
If you storeUserbut read asStudent, Json deserialization exception will occur. - Easy‑to‑miss null check for default(T)
var model = Get<User>("key");
// model returns null for missing reference‑type key, accessing model.Name directly causes null reference exception
if(model != null)
{
}Code language: C# (cs)
- Unified encoding
Must use consistentEncoding.UTF8for write and read, otherwise garbled text appears.
Read value
Previous: Write value
Next: Check existence