Implementation of C#Cache

Cache implementation

Instead of caching third-party implementations such as Redis, we do some environment variables based on C# to facilitate project use.

1. System Global Variables

Many times, at the beginning of the system operation, the system operation parameters need to be saved for global use.

The code is as follows:

 public class PFTCacheObject
    {
        /// <summary>
        ///Dictionary
        /// </summary>
        private static Dictionary<string, object> _dataDic = new Dictionary<string, object>();


        /// <summary>
        ///Define a static variable to hold an instance of a class
        /// </summary>
        private static PFTCacheObject _session;

        /// <summary>
        ///Define an identity to ensure thread synchronization
        /// </summary>
        private static readonly object _locker = new object();


        /// <summary>
        ///singleton
        /// </summary>
        /// <returns>The return type is Session</returns>
        public static PFTCacheObject Instance
        {
            get
            {
                if (_session == null)
                {
                    lock (_locker)
                    {
                        if (_session == null)// Create an instance of the class if it does not exist, otherwise return directly
                        {
                            _session = new PFTCacheObject();
                        }
                    }
                }
                return _session;
            }
        }

        #region Remove Removal

        /// <summary>
        ///Delete members
        /// </summary>
        /// <param name="name"></param>
        public void Remove(string name)
        {
            _dataDic.Remove(name);
        }

        /// <summary>
        ///Remove all members
        /// </summary>
        public void RemoveAll()
        {
            _dataDic.Clear();
        }
        #endregion

        #The indexer for the region class

        /// <summary>
        ///Indexer of this class
        /// </summary>
        /// <returns>Return Object member </returns>
        public Object this[string index]
        {
            get
            {
                if (_dataDic.ContainsKey(index))
                {
                    Object obj = (Object)_dataDic[index];
                    return obj;
                }
                return null;
            }
            set
            {
                if (_dataDic.ContainsKey(index))
                {
                    _dataDic.Remove(index);
                }
                _dataDic.Add(index, value);
            }
        }
        #endregion


    }

This is saved using a static variable, Dictionary, where all items are directly available.

2. Asynchronous data caching

On the web, HttpContext.Current.Items are often used for data caching, and CallContext.LogicalSetData is used on the.Net Framework framework.CallContext.LogicalSetData is no longer available on.Net Standard, and its replacement is AsyncLocal.Because we're all using.Net Standard now, and our project is not just web, we're just using AsyncLocal here.

The code is as follows

public class PFTCallContext
    {

        #region Shared Database Connection

        private static AsyncLocal<object> _asyncLocalConnectionOject = new AsyncLocal<object>();

        /// <summary>
        ///Set Shared Database Connection
        /// </summary>
        /// <param name="obj"></param>
        public static void SetConnectionOject(object obj)
        {
            _asyncLocalConnectionOject.Value = obj;
        }

        /// <summary>
        ///Get a shared database connection
        /// </summary>
        /// <returns></returns>
        public static object GetConnectionOject()
        {
            return _asyncLocalConnectionOject.Value;
        }

        /// <summary>
        ///Clear Shared Database Connection
        /// </summary>
        public static void ClearConnectionOject()
        {
            _asyncLocalConnectionOject.Value = null;
        }

        #endregion



    }

Here we define a cache for the current database connection object.If you need another definition, you can do it directly.

3..Net Core's MooryCache

This one wanted to use cache in the.Net Framework framework, but.Net Core is the future, and.Net Framework has many implementations of cache, so I'll use the. Net Core's MooryCache directly here.The.Net Core snail is also learning, and related API s are being studied. If you have problems, please help correct them.

public static class PFTCache
    {
        public readonly static IMemoryCache _memoryCache;

        static PFTCache()
        {
            _memoryCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));
        }

        #region General Cache
        /// <summary>
        ///Get Cached Value
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static Object GetCache(string key)
        {
            return _memoryCache.Get(key);
        }
        /// <summary>
        ///Remove Cache
        /// </summary>
        /// <param name="key"></param>
        public static void Remove(string key)
        {
            _memoryCache.Remove(key);
        }
        /// <summary>
        ///Set Cache
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetCache(string key, Object value)
        {
            _memoryCache.GetOrCreate(key, entry =>
            {
                return value;
            });
        }
        /// <summary>
        ///Set cache (fixed time expiration)
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="absoluteExpiration"></param>
        public static void SetCacheAbsolute(string key, Object value, int absoluteExpiration)
        {
            _memoryCache.GetOrCreate(key, entry =>
            {

                entry.SetAbsoluteExpiration(TimeSpan.FromSeconds(absoluteExpiration));
                return value;
            });
        }
        /// <summary>
        ///Set cache (scroll time expires)
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="slidingExpiration"></param>
        public static void SetCacheSliding(string key, Object value, int slidingExpiration)
        {
            _memoryCache.GetOrCreate(key, entry =>
            {

                entry.SetSlidingExpiration(TimeSpan.FromSeconds(slidingExpiration));
                return value;
            });
        }

        #endregion

        #region File Dependency Cache
        /// <summary>
        ///File Dependent Cache
        /// </summary>
        /// <param name="key"></param>
        /// <param name="fullName"></param>
        /// <returns></returns>
        public static string DependentCacheFile(string key, string fullName)
        {
            var basePath = PFTFile.GetDirectoryName(fullName);
            var fileName = PFTFile.GetFileName(fullName);
            var fileProvider = new PhysicalFileProvider(basePath);
            return _memoryCache.GetOrCreate(key, entry =>
            {
                entry.AddExpirationToken(fileProvider.Watch(fileName));
                return PFTFile.IsExistFile(fullName) ? PFTFile.ReadFile(fullName) : string.Empty;
            });
        }
        #endregion

    }

Okay, let's start with caching this snail.

Tags: C# Database FileProvider Redis Session

Posted on Sun, 22 Sep 2019 12:43:27 -0400 by dipenmistry