Last active
January 3, 2019 01:00
-
-
Save poychang/14318fcd5c576ccd6048fadc55b420c8 to your computer and use it in GitHub Desktop.
[將物件做二進位序列化後存至 Redis 中] #dotnet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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