幽梦紫曦

redis运行时缓存设置

电脑版发表于:2020/3/31 16:03

1.判断是否有此key的值.类库(CacheHelper)

注:如果要获取缓存数据,请使用TryGetValue方法

public static bool Contains(string key)

        {

            if (HttpRuntime.Cache[key] != null)

            {

                return true;

            }

            else

            {

                return false;

            }

        }

2.通过缓存键获取相应的内容

public static T Get<T>(string key)

        {

            return (T)HttpRuntime.Cache[key];

        }

3.新增,添加缓存(如果缓存键已经存在,则此方法调用无效)

public static void Set<T>(string key, T value, TimeSpan tspan)

        {

            HttpRuntime.Cache.Add(key, value, null, DateTime.Now.Add(tspan),

                TimeSpan.Zero, CacheItemPriority.NotRemovable, null);

        }

//redis运行时缓存设置

public static T GetSetRuntimeCache<T>(string key, Func<T> act, TimeSpan? timeSpan)

        {

            if (CacheHelper.Contains(key))

            {

                return CacheHelper.Get<T>(key);

            }

            var obj = act();


            if (timeSpan != TimeSpan.Zero)

            {

                CacheHelper.Set(key, obj, timeSpan.Value);

            }

            return obj;

        }


关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢