Microsoft.Extensions.Caching.CSRedis icon indicating copy to clipboard operation
Microsoft.Extensions.Caching.CSRedis copied to clipboard

增加缓存对象扩展方法

Open 2881099 opened this issue 7 years ago • 2 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);
	}
}

2881099 avatar Sep 29 '18 20:09 2881099

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

ZeeLyn avatar Nov 28 '18 04:11 ZeeLyn

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

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

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

2881099 avatar Nov 28 '18 06:11 2881099