给IDistributedCache新增了扩展方法GetOrCreate、GetOrCreateAsync

时间:2023-03-10 08:39:06
给IDistributedCache新增了扩展方法GetOrCreate、GetOrCreateAsync
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