Write value

StackExchange.Redis Generic Set / Get for write‑and‑read operations

  1. Underlying call: IDatabase.StringSet() to write Redis string‑type data
  2. Serialization logic: arbitrary object → JSON string → UTF8 byte array stored into Redis
  3. Deserialization logic: read byte array → JSON string → target generic object
  4. Return value: true = success, false = failure

Required namespaces

using StackExchange.Redis;
using Newtonsoft.Json;
using System.Text;Code language: CSS (css)

The example below uses Set, accepts a key, byte array, and expiration duration.

/// <summary>
/// Write cache entry to Redis
/// </summary>
/// <param name="key">Cache key</param>
/// <param name="data">Any object instance</param>
/// <param name="cacheTime">Expiration time 【minutes】</param>
/// <returns>true for success / false for failure</returns>
private bool Set(string key, object data, int cacheTime)
{
    if (data == null)
    {
        return false;
    }
    byte[] entryBytes = Serialize(data);
    TimeSpan expiresIn = TimeSpan.FromMinutes(cacheTime);
    return db.StringSet(key, entryBytes, expiresIn);
}

/// <summary>
/// Object serialization: object → byte[]
/// </summary>
private byte[] Serialize(object data)
{
    string json = JsonConvert.SerializeObject(data);
    return Encoding.UTF8.GetBytes(json);
}

/// <summary>
/// Read cached value by key
/// </summary>
/// <typeparam name="T">Target object type</typeparam>
/// <param name="key">Cache key</param>
/// <returns>default(T) if key does not exist</returns>
public T Get<T>(string key)
{
    RedisValue rValue = db.StringGet(key);
    if (!rValue.HasValue)
    {
        return default(T);
    }
    T result = Deserialize<T>(rValue);
    return result;
}

/// <summary>
/// Deserialization: byte[] → T object
/// </summary>
private T Deserialize<T>(byte[] serializedObject)
{
    if (serializedObject == null)
    {
        return default(T);
    }
    string json = Encoding.UTF8.GetString(serializedObject);
    return JsonConvert.DeserializeObject<T>(json);
}Code language: PHP (php)

Notes

  1. Time unit
    In code TimeSpan.FromMinutes(cacheTime) means input value represents 【minutes】
    If you call Set(key,val,1000) from your form, cache will expire after 1000 minutes, NOT seconds!

The earlier WinForms sample used hard‑coded 1000, this is a common pitfall.
If you need to pass seconds, replace with TimeSpan.FromSeconds(cacheTime)

  1. Dependencies installation
    Install both NuGet packages:
  • StackExchange.Redis
  • Newtonsoft.Json
  1. Data storage format
    All objects are serialized to JSON binary and stored inside Redis; values viewed in Redis client are standard JSON text.
  2. RedisValue compatibility
    db.StringGet(key) returns RedisValue, it supports implicit conversion to byte[] and can be passed directly into Deserialize<T>.
  3. Thread‑safety suggestion
    IConnectionMultiplexer should be global singleton. Do not create new connection on every Redis read‑write.

Usage example

// Write entry (expire after 30 minutes)
bool ok = Set("user:1001", new {Id = 1001, Name = "test"}, 30);

// Read value
var user = Get<dynamic>("user:1001");

// Read model entity example
// var model = Get<UserInfo>("user:1001");Code language: JavaScript (javascript)

Recommendations

Extract these helper methods together with Redis connection logic into a standalone static helper class RedisHelper.cs. Avoid putting them inside Form code for better separation‑of‑concerns.

Write value

Leave a Reply

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