Home  >  Article  >  Backend Development  >  .net cache - file-based caching

.net cache - file-based caching

黄舟
黄舟Original
2017-02-24 10:46:462345browse


1. Basic knowledge of caching in .Net

Two dependencies supported in .net:


CacheDependency

##SqlDependency

indicates dependence on files or directories

indicates dependence on SQL Database dependencies

Expiration time


Absolute expiration time

Sliding expiration time

A specific point in time, type is DateTime

##One Time interval, type is TimeSpan


#Priority: CacheItemPriority

Since we need to cache a large amount of data, when memory is limited, the cached data must be prioritized so that unimportant data can be removed from the cache when needed. Priority is used to specify the importance of cached data. Important data can be kept in memory for a longer period of time.


Delete notification Can be provided when cached data is removed from memory A notification mechanism to call back user-defined methods, which must conform to the definition of the CacheItemRemovedCallback delegate. .


Special Note: 1. The timing of a callback is unpredictable and cannot be assumed to occur. When, the execution thread of the callback method has the context of HttpContext. In order to obtain a reference to the Cache object when there is no request context, you can use the application's cache through the cache attribute of HttpRuntime.


2. You cannot use instance methods as callback methods on the page. When using the callback method on the page, the reference pointing to the callback method will prevent the garbage collection mechanism, so the memory will be exhausted quickly.


3. Generally, the callback method is implemented through the static method of the custom class, or using the static method of the page object.

Second, file-based caching example

First add a label on the test page:

  <asp:Label Text="" runat="server" id="label1"/>
Next, add the cache management class:

<span style="font-size:14px;">namespace 基于文件的缓存依赖
{
    public class CacheManager
    {
        public static string Message {

            get {
                HttpContext context = HttpContext.Current;

                //首先从缓存中获取
                string message = context.Cache["Message"] as string;

                //如果缓存中没有数据
                if (message==null)
                {
                    string path = context.Server.MapPath("TestFileCache.txt");
                    message = System.IO.File.ReadAllText(path);

                    //将信息保存到缓存中,设置响应的过期时间为1分钟
                    context.Cache.Add(
                        "Message",
                        message,
                        new System.Web.Caching.CacheDependency(path),//依赖于文件或者目录的依赖
                        System.Web.Caching.Cache.NoAbsoluteExpiration,//不使用绝对过期时间
                        new TimeSpan(0, 0, 5),//缓存的时间
                        System.Web.Caching.CacheItemPriority.Normal, //缓存的优先级
                        Callback); //过期时的回调
                    
                }

                return message;
            }
        
        }


        /// <summary>
        /// Callbacks the specified key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <param name="reason">The reason.</param>
        /// <remarks>Editor:v-liuhch CreateTime:2015/5/26 20:13:22</remarks>
        private static void Callback(
            
            string key,
            Object value,
            System.Web.Caching.CacheItemRemovedReason reason
            //原因
            ) {

                if (reason == System.Web.Caching.CacheItemRemovedReason.Expired)
                {
                   HttpRuntime.Cache.Insert("Message","时间已到,缓存已过期");
                    
                }
                }
           
        
        }

}</span>
Here, distinguish the Add method and Insert method of cache:

## When calling Add, if the cache item to be added exists, it will The call fails; but if insert is used, the newly inserted value will overwrite the original value.

In webform1, add a line to test:

 protected void Page_Load(object sender, EventArgs e)
        {
                this.label1.Text = CacheManager.Message;   //获取缓存

        }

You can see that the content in the file has been read. Because it is set to expire after 5s, we refresh it after 5s:

However, through multiple tests we will find that the exact time when expiration occurs after refreshing is not 5s, and it has also been verified that the timing of the callback is unpredictable.

.

The above is the content of .net cache-file-based cache. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn