Read value

Redis Get Value

  1. Underlying API:IDatabase.StringGet(key), reads string‑type data from Redis, returns RedisValue
  2. RedisValue.HasValue:Check whether the key exists and contains valid data
    • true:Key exists;
    • false:Key does not exist
  3. After fetching binary data, you need to deserialize it to restore the original object
  4. 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

  1. Implicit type conversion
    RedisValue supports direct implicit conversion to byte[], you can pass rValue directly into Deserialize<T>(byte[]), compiler handles conversion automatically.
  2. Paired read‑write workflow
Set write flowEntitySerializebyte[]Redis
Get read flowRedisbyte[]DeserializeEntityCode language: CSS (css)
  1. 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)
  1. Mismatched serialize‑deserialize types
    If you store User but read as Student, Json deserialization exception will occur.
  2. 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)
  1. Unified encoding
    Must use consistent Encoding.UTF8 for write and read, otherwise garbled text appears.

Read value

Leave a Reply

Your email address will not be published. Required fields are marked *