StackExchange.Redis Generic Set / Get for write‑and‑read operations
- Underlying call:
IDatabase.StringSet()to write Redis string‑type data - Serialization logic: arbitrary object → JSON string → UTF8 byte array stored into Redis
- Deserialization logic: read byte array → JSON string → target generic object
- 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
- Time unit
In codeTimeSpan.FromMinutes(cacheTime)means input value represents 【minutes】
If you callSet(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 withTimeSpan.FromSeconds(cacheTime)
- Dependencies installation
Install both NuGet packages:
StackExchange.RedisNewtonsoft.Json
- Data storage format
All objects are serialized to JSON binary and stored inside Redis; values viewed in Redis client are standard JSON text. RedisValuecompatibilitydb.StringGet(key)returnsRedisValue, it supports implicit conversion tobyte[]and can be passed directly intoDeserialize<T>.- Thread‑safety suggestion
IConnectionMultiplexershould 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
Previous: Connect to Redis