zoukankan      html  css  js  c++  java
  • 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;

  • 相关阅读:
    Apache ActiveMQ消息中间件的基本使用
    struts2结合生成验证码
    Python中docstring文档的写法
    Nginx+uWSGI+Django原理
    Python垃圾回收机制详解
    Python数据库连接池实例——PooledDB
    构建高可用服务端
    Python使用multiprocessing实现一个最简单的分布式作业调度系统
    python3 分布式进程(跨机器)BaseManager(multiprocessing.managers)
    python BaseManager分布式学习
  • 原文地址:https://www.cnblogs.com/hn_lijia/p/11331933.html
Copyright © 2011-2022 走看看