1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Caching;
- using System.Web;
- namespace Central.Control.WebApi.Cache
- {
- /// <summary>
- ///
- /// </summary>
- public class CacheHelper: ICacheHelper
- {
- private MemoryCache _cache = MemoryCache.Default;
- /// <summary>
- /// 此方法缓存不会过期,请谨慎使用
- /// </summary>
- /// <param name="key"></param>
- /// <param name="content"></param>
- public void SetByNotExpired<T>(string key, T content)
- {
- var policy = new CacheItemPolicy
- {
- AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration
- };
- _cache.Set(key, content, policy);
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="key"></param>
- /// <param name="content"></param>
- /// <param name="seconds"></param>
- public void Set<T>(string key, T content, int seconds = 300)
- {
- var policy = new CacheItemPolicy
- {
- AbsoluteExpiration = DateTime.Now.AddSeconds(seconds)
- };
- policy.AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration;
- // System.Runtime.Caching.ObjectCache.InfiniteAbsoluteExpiration
- _cache.Set(key, content, policy);
- }
- /// <summary>
- ///
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="key"></param>
- /// <returns></returns>
- public T Get<T>(string key) where T : class
- {
- if (_cache.Contains(key))
- {
- return _cache[key] as T;
- }
- return null;
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="key"></param>
- public void Remove(string key)
- {
- _cache.Remove(key);
- }
- }
- }
|