淺談Redis
阿新 • • 發佈:2018-03-31
字符串 緩存 讀取 return des () obj 高可用 red
Redis,內存中的數據結構存儲,作為數據庫,緩存和消息代理。它支持的數據結構,如字符串、哈希表、列表、設置、排序設置範圍查詢,位圖,hyperloglogs和半徑查詢地理信息的索引。
使用內置的復制,Lua腳本,LRU逐出,磁盤上的持久性交易和不同等級,並且可以通過Redis的前哨和自動分區Redis集群高可用性。為了實現其出色的表現,Redis是工作在內存中的數據集
實現簡單的讀寫
一、新建一個控制臺項目
1、NuGet安裝
2、寫入
ConnectionMultiplexer con = RedisConnection.Connection; IDatabase db = con.GetDatabase(1);//不寫默認是連接到數據庫0 Student st = new Student { Age=12,Name="yuan",School="TaiKang"}; db.Set("student",st);
3、效果如圖
4、讀取
ConnectionMultiplexer con = RedisConnection.Connection; IDatabase db = con.GetDatabase(1);//不寫默認是連接到數據庫0 Student st = new Student(); st = db.Get<Student>("student");
二、輔助類
1、實體
[Serializable] public class Student { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } public string School { get; set; } }
2、鏈接數據庫(Redis)
public class RedisConnection { privatestatic readonly Lazy<ConnectionMultiplexer> _connection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect("localhost:6379")); public static ConnectionMultiplexer Connection { get { return _connection.Value; } } }
3、方法
public static class RedisExtension { public static TResult Get<TResult>(this IDatabase cache, string key) { return Deserialize<TResult>(cache.StringGet(key)); } public static void Set<TIn>(this IDatabase cache, string key, TIn value) { cache.StringSet(key, Serialize(value)); } static byte[] Serialize(object o) { if (o == null) return null; BinaryFormatter binaryFormatter = new BinaryFormatter(); using (MemoryStream mStream = new MemoryStream()) { binaryFormatter.Serialize(mStream, o); byte[] objectDataAsStream = mStream.ToArray(); return objectDataAsStream; } } static TResult Deserialize<TResult>(byte[] stream) { if (stream == null) return default(TResult); BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream memStream = new MemoryStream(stream)) { TResult result = (TResult)formatter.Deserialize(memStream); return result; } } }
淺談Redis