Skip to content

Instantly share code, notes, and snippets.

@poychang
Last active January 3, 2019 01:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poychang/14318fcd5c576ccd6048fadc55b420c8 to your computer and use it in GitHub Desktop.
Save poychang/14318fcd5c576ccd6048fadc55b420c8 to your computer and use it in GitHub Desktop.
[將物件做二進位序列化後存至 Redis 中] #dotnet
void Main()
{
//Can StackExchange.Redis be used to store POCO?
//https://stackoverflow.com/questions/27857945/can-stackexchange-redis-be-used-to-store-poco
var connection = ConnectionMultiplexer.Connect("YOUR_REDIS_SERVER_CONNECTION_STRING");
var db = connection.GetDatabase();
var data = new PocoType { Id = 1, Name = "YouNameIt", List = new List<string> { "A", "B", "C" } };
Write<PocoType>(db, data);
Read<PocoType>(db).Dump();
}
// Define other methods and classes here
[Serializable]
public class PocoType
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<string> List { get; set; }
}
public void Write<T>(IDatabase db, T data)
{
var key = "RedisKey";
byte[] bytes;
using (var stream = new MemoryStream())
{
new BinaryFormatter().Serialize(stream, data);
bytes = stream.ToArray();
}
db.StringSet(key, bytes, TimeSpan.FromMinutes(1));
}
public T Read<T>(IDatabase db)
{
var key = "RedisKey";
byte[] bytes = (byte[])db.StringGet(key);
if (bytes != null)
{
using (var stream = new MemoryStream(bytes))
{
return (T)new BinaryFormatter().Deserialize(stream);
}
}
return default(T);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment