欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-01-21 09:57:46
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