给IDistributedCache新增了扩展方法GetOrCreate、GetOrCreateAsync
程序员文章站
2023-12-24 14:43:39
public static class DistributedCacheExtensions { public static TItem GetOrCreate(this IDistributedCache cache, string key, Func factory) { TItem t = d... ......
public static class distributedcacheextensions { public static titem getorcreate<titem>(this idistributedcache cache, string key, func<distributedcacheentryoptions, titem> factory) { titem t = default(titem); byte[] vs = cache.get(key); if (vs == null) { var options = new distributedcacheentryoptions(); t = factory.invoke(options); cache.set(key, messagepack.messagepackserializer.serialize<titem>(t), options); } else { t = messagepack.messagepackserializer.deserialize<titem>(vs); } return t; } public static async task<titem> getorcreateasync<titem>(this idistributedcache cache, string key, func<distributedcacheentryoptions, task<titem>> factory) { titem t = default(titem); byte[] vs = cache.get(key); if (vs == null) { var options = new distributedcacheentryoptions(); t = await factory.invoke(options); await cache.setasync(key, messagepack.messagepackserializer.serialize<titem>(t), options); } else { t = messagepack.messagepackserializer.deserialize<titem>(vs); } return t; } }
user user = _distributedcache.getorcreate("key", (options) => { options.absoluteexpirationrelativetonow = timespan.fromseconds(20); return new user { id = 1, name = "bidianqing" }; });
[datacontract] public class user { [datamember(order =0)] public int id { get; set; } [datamember(order = 1)] public string name { get; set; } }
install-package messagepack