• C#缓存


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime;
    using System.Runtime.Caching;

    namespace BD.EAS_jinantianhui
    {
    public class CacheHelper
    {
    private static readonly Object _locker = new object();

    public static T GetCacheItem<T>(String key, Func<T> cachePopulate, TimeSpan? slidingExpiration = null, DateTime? absoluteExpiration = null)
    {
    if (String.IsNullOrWhiteSpace(key)) throw new ArgumentException("Invalid cache key");
    if (cachePopulate == null) throw new ArgumentNullException("cachePopulate");
    if (slidingExpiration == null && absoluteExpiration == null) throw new ArgumentException("Either a sliding expiration or absolute must be provided");

    if (MemoryCache.Default[key] == null)
    {
    lock (_locker)
    {
    if (MemoryCache.Default[key] == null)
    {
    var item = new CacheItem(key, cachePopulate());
    var policy = CreatePolicy(slidingExpiration, absoluteExpiration);

    MemoryCache.Default.Add(item, policy);
    }
    }
    }

    return (T)MemoryCache.Default[key];
    }

    private static CacheItemPolicy CreatePolicy(TimeSpan? slidingExpiration, DateTime? absoluteExpiration)
    {
    var policy = new CacheItemPolicy();

    if (absoluteExpiration.HasValue)
    {
    policy.AbsoluteExpiration = absoluteExpiration.Value;
    }
    else if (slidingExpiration.HasValue)
    {
    policy.SlidingExpiration = slidingExpiration.Value;
    }

    policy.Priority = CacheItemPriority.Default;

    return policy;
    }
    // <summary>
    /// 清空缓存
    /// </summary>
    public static void ClearCache()
    {
    List<string> cacheKeys = MemoryCache.Default.Select(kvp => kvp.Key).ToList();
    foreach (string cacheKey in cacheKeys)
    {
    MemoryCache.Default.Remove(cacheKey);
    }
    }
    }
    }

    使用方式:

    WSContext context = MemoryCache.Default["WSContext"] as WSContext;
    if (null == context)
    {
    context = service.login(easUser, easPass, "eas", easCRMdata, "L2", int.Parse(easDBType));
    if (null != context)
    {
    CacheHelper.GetCacheItem<WSContext>("WSContext", delegate () { return context; }, new TimeSpan(0, 30, 0));//30分钟过期
    return context;
    }
    }
    return context;

  • 相关阅读:
    Jenkins安装2
    11月14 vagrant 虚拟机连接
    11月13 ssh 和 netstat
    Jenkins安装
    11月12号 springboot1.5 引入redis
    11月12号 用户登录输入密码错误达到指定次数后,锁定账户 004
    js模式-观察者模式
    立即执行函数
    vue 获取数据
    在登陆退出时候使用Vuex
  • 原文地址:https://www.cnblogs.com/hn_lijia/p/11331933.html
Copyright © 2020-2023  润新知