2881099 / Microsoft.Extensions.Caching.CSRedis

分布式缓存,替代 Microsoft.Extensions.Caching.Redis

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

增加缓存对象扩展方法

2881099 opened this issue · comments

using Microsoft.Extensions.Caching.Distributed;

IDistributedCache cache = xxxx;

object obj1 = new xxxx();
cache.SetObject("key1", obj1);

object obj2 = cache.GetObject("key1");
T obj3 = cache.GetObject<T>("key1");

内部使用 BinaryFormatter 序列化/反序列化

public static byte[] Serialize(object value) {
	using (MemoryStream ms = new MemoryStream()) {
		IFormatter formatter = new BinaryFormatter();
		formatter.Serialize(ms, value);
		return ms.GetBuffer();
	}
}
public static object Deserialize(byte[] stream) {
	using (MemoryStream ms = new MemoryStream(stream)) {
		IFormatter formatter = new BinaryFormatter();
		return formatter.Deserialize(ms);
	}
}

被序列化的对象必须加SerializableAttribute才能序列化,使用起来很不方便

这里暂时不方便改动了,因为已经有同学在使用

如果觉得不方便可以扩展一系列 IDistributedCache 方法

参考:https://github.com/2881099/Microsoft.Extensions.Caching.CSRedis/blob/master/IDistributedCacheExtensions.cs