C # cache implementation

Cache implementation

We're not a third party such as Redis cache implementation, etc., but the actual situation, based on C # do something to save the environment variables for easy project.

1, the system of global variables

In many cases, the system began to run, we need to save the operating parameters of the system, so for global use.

code show as below:

 public  class PFTCacheObject 
    { /// <Summary> /// dictionary /// </ Summary> Private static the Dictionary < String , Object > = _dataDic new new the Dictionary < String , Object > (); /// <Summary> /// examples defines a static class variable to hold /// </ Summary> Private static PFTCacheObject _SESSION; /// <Summary> /// identifier is defined to ensure a thread synchronization /// </ Summary> Private static Readonly Object _locker = new new Object (); /// <Summary> /// singleton
        
        
        
         


        
        
        
         

        
        
        
            


        
        
        /// </ Summary> 
        /// <Returns> return type of the Session </ Returns> 
        public  static PFTCacheObject Instance 
        { GET 
            { IF (_SESSION == null ) 
                { Lock (_locker) 
                    { IF (_SESSION == null ) // If an instance of the class does not exist it is created, otherwise it returns directly 
                        { 
                            _SESSION = new new PFTCacheObject (); 
                        } 
                    } 
                } return _SESSION; 
            } 
        }
            
                
                    
                        
                

        #region Remove removed /// <Summary> /// remove members /// </ Summary> /// <param name = "name"> </ param> public void the Remove ( String name) 
        { 
            _dataDic.Remove ( name); 
        } /// <summary> /// remove all members /// </ Summary> public void the RemoveAll () 
        { 
            _dataDic.Clear (); 
        } 
        #endregion 
        #region of this class indexer /// <summary > /// this class index is /// </ Summary> /// <returns> Back Object members </ 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


    }

As used herein, Dictionary a static variable to save, all projects can be obtained directly.

2, the asynchronous data buffer

Available on the web, often it is used in HttpContext.Current.Items caching of the data used in the .Net Framework CallContext.LogicalSetData frame. In .Net Standard above CallContext.LogicalSetData no longer be used to replace his method is AsyncLocal. Because we are now using .Net Standard, and our project is not just web, so here we only use AsyncLocal achieve.

code show as below

public  class PFTCallContext 
    { 

        #region shared database connection Private static AsyncLocal < Object > = _asyncLocalConnectionOject new new AsyncLocal < Object > (); /// <Summary> /// set the shared database connection /// </ Summary> /// <param = name "obj"> </ param> public static void SetConnectionOject ( Object obj) 
        { 
            _asyncLocalConnectionOject.Value = obj; 
        } /// <Summary> /// Gets a shared database connection /// </ Summary> /// < returns> </ returns>public static object

         

        
        
        
        
          

        
        
        
        
           GetConnectionOject()
        {
            return _asyncLocalConnectionOject.Value;
        }

        /// <summary>
        /// 清空共享数据库连接
        /// </summary>
        public static void ClearConnectionOject()
        {
            _asyncLocalConnectionOject.Value = null;
        }

        #endregion



    }

Here we first define a current cache database connection object. If you need other definitions, you can directly implement.

3, .Net Core of MemoryCache

Originally I wanted to use this cache .Net Framework framework, but .Net Core is the future trend, and .Net Framework has a lot of cache implementation method, so here I am on the direct use of .Net Core MemoryCache. .Net Core snails are learning, but also continuous research related API, if there is a problem, please help correct.

public static class PFTCache
    {
        public readonly static IMemoryCache _memoryCache;

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

        #region 常规缓存
        /// <summary>
        /// 获取缓存的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static Object GetCache(string key)
        {
            return _memoryCache.Get(key);
        }
        /// <summary>
        /// 移除缓存
        /// </summary>
        /// <param name="key"></param>
        public static void Remove(string key)
        {
            _memoryCache.Remove(key);
        }
        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetCache(string key, Object value)
        {
            _memoryCache.GetOrCreate(key, entry =>
            {
                return value;
            });
        }
        /// <summary>
        /// 设置缓存(固定时间过期)
        /// </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));returnvalue;
            });
        }/// <summary>/// </ the Summary>/// set the cache (scroll time expired)
                 
        
        
        
        /// <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 文件依赖缓存
        /// <summary>
        /// 文件依赖缓存
        /// </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 

    }

Well, on this piece of snail cache on the first stop here.

Guess you like

Origin www.cnblogs.com/snailblog/p/11570094.html