[Reprint] Simple implementation of native cache in C#

Cache interface class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo.Code
{
    public interface ICache
    {
        T GetCache<T>(string cacheKey) where T : class;//Read the cache
        void WriteCache<T>(T value, string cacheKey) where T : class;//更新缓存
        void WriteCache<T>(T value, string cacheKey, DateTime expireTime) where T : class;//Update the cache and set the expiration time
        void RemoveCache(string cacheKey);//Remove the cache with the specified name
        void RemoveCache();//Remove all caches
    }
}

Interface implementation:

using System;
using System.Collections;
using System.Web;


namespace Demo.Code
{
    public class Cache : ICache
    {
        private static System.Web.Caching.Cache cache = HttpRuntime.Cache;

        public T GetCache<T>(string cacheKey) where T : class
        {
            if (cache[cacheKey] != null)
            {
                return (T)cache[cacheKey];
            }
            return default(T);
        }
        public void WriteCache<T>(T value, string cacheKey) where T : class
        {
            cache.Insert(cacheKey, value, null, DateTime.Now.AddMinutes(10), System.Web.Caching.Cache.NoSlidingExpiration);
        }
        public void WriteCache<T>(T value, string cacheKey, DateTime expireTime) where T : class
        {
            cache.Insert(cacheKey, value, null, expireTime, System.Web.Caching.Cache.NoSlidingExpiration);
        }
        public void RemoveCache(string cacheKey)
        {
            cache.Remove(cacheKey);
        }
        public void RemoveCache()
        {
            IDictionaryEnumerator CacheEnum = cache.GetEnumerator();
            while (CacheEnum.MoveNext())
            {
                cache.Remove(CacheEnum.Key.ToString());
            }
        }
    }
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326484128&siteId=291194637