1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using Bowin.Common.JSON;
- using Microsoft.Extensions.Caching.Memory;
- using Microsoft.Extensions.DependencyInjection;
- namespace Bowin.Common.Cache
- {
- public class MemoryCacheProvider : ICacheProvider
- {
- private IMemoryCache cache { get; set; }
- public MemoryCacheProvider()
- { }
- public MemoryCacheProvider(IMemoryCache _cache)
- {
- cache = _cache;
- }
- //private static MemoryCache cache
- //{
- // get
- // {
- // return new MemoryCache(new MemoryCacheOptions { });
- // }
- //}
- public void Config(IServiceCollection service)
- {
- service.AddMemoryCache();
- }
- public object Add(string key, object entry)
- {
- var result = Get(key);
- if (result != null)
- {
- cache.Remove(key);
- }
- using (var cacheEntry = cache.CreateEntry(key))
- {
- cacheEntry.AbsoluteExpiration = DateTime.Now.AddYears(2);
- cacheEntry.Value = entry;
- }
- result = entry;
- return result;
- }
- public object Add(string key, object entry, DateTime utcExpiry)
- {
- var result = Get(key);
- if (result != null)
- {
- cache.Remove(key);
- }
- using (var cacheEntry = cache.CreateEntry(key))
- {
- cacheEntry.AbsoluteExpiration = utcExpiry;
- cacheEntry.Value = entry;
- }
- result = entry;
- return result;
- }
- public object Get(string key)
- {
- object result;
- if (cache.TryGetValue(key, out result))
- {
- return result;
- }
- else
- {
- return null;
- }
- }
- public void Remove(string key)
- {
- cache.Remove(key);
- }
- public void Set(string key, object entry)
- {
- Add(key, entry);
- }
- public void Set(string key, object entry, DateTime utcExpiry)
- {
- Add(key, entry, utcExpiry);
- }
- }
- }
|