.NET的缓存机制

时间:2016-05-09 14:17:34

标签: c# database caching

***Just for learning purpose***

最近我只知道缓存和缓存机制一词,并且通常理解缓存机制对系统响应性能是一件好事,并减少许多与数据库的交互。

基于与其他人的交谈,他们告诉我一般的想法,我们可以创建一个独立的库并缓存从数据库检索的数据,一旦我们需要它在我们的业务层,那么我们可以从缓存中检索它层。

他们还分享了一些但不是非常详细的数据库,当数据库刷新数据时,数据库可以自动更新缓存层,如更新,添加和删除。

所以我的问题来了,数据库如何主动和自动地知道和更新缓存层?有人可以与我分享一些东西吗?或者是否存在任何现有框架,开源解决方案?

我非常感谢您的亲切帮助。我很期待收到你朋友的来信。

2 个答案:

答案 0 :(得分:1)

试试这个第三方缓存:CacheCrow,它是一个简单的基于LFU的缓存。

在visual studio中使用powershell命令安装:Install-Package CacheCrow

代码段:

// initialization of singleton class
ICacheCrow<string, string> cache = CacheCrow<string, string>.Initialize(1000);

// adding value to cache
cache.Add("#12","Jack");

// searching value in cache
var flag = cache.LookUp("#12");
if(flag)
{
    Console.WriteLine("Found");
}

// removing value
var value = cache.Remove("#12");

有关详细信息,请访问:https://github.com/RishabKumar/CacheCrow

答案 1 :(得分:0)

雅各

让我举个例子......

在数据层中,当我们要检索应该从数据库缓存的对象列表时,我们可以这样做。

if (!CacheHelper.Get("AllRoles", out entities))   
{
var items = _context.Set<Roles>().ToList();
entities = items;
var cachableEntities = entities.ToList();
CacheHelper.Add(cachableEntities, "AllRoles");
}

return entities;

你会注意到我有一个缓存助手,它会在缓存中搜索密钥“AllRoles”,如果找到缓存,它将从缓存中返回实体。如果找不到它,它将从数据库中获取数据并使用密钥创建缓存。

此外,每次我们添加/删除/或更改此表中的项目时,我们都可以简单地销毁此缓存。

CacheHelper.Clear(CacheKey);

回答这个问题,在这个示例中,数据库不知道何时重新创建缓存,应用程序逻辑确实如此。

这里有一个你可以使用的缓存助手样本......

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

namespace Core.Helpers
{
    public static class CacheHelper
    {
        public static List<string> GetCacheKeys()
        {
            List<string> keys = new List<string>();
            // retrieve application Cache enumerator
            var enumerator = System.Web.HttpRuntime.Cache.GetEnumerator();

            while (enumerator.MoveNext())
            {
                keys.Add(enumerator.Key.ToString());
            }

            return keys;
        }

        /// <summary>
        /// Insert value into the cache using
        /// appropriate name/value pairs
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="o">Item to be cached</param>
        /// <param name="key">Name of item</param>
        public static void Add<T>(T o, string key)
        {
            // NOTE: Apply expiration parameters as you see fit.
            // I typically pull from configuration file.

            // In this example, I want an absolute
            // timeout so changes will always be reflected
            // at that time. Hence, the NoSlidingExpiration.
            if (HttpContext.Current != null)
            HttpContext.Current.Cache.Insert(
                key,
                o,
                null,
                DateTime.Now.AddMinutes(1440),
                System.Web.Caching.Cache.NoSlidingExpiration);
        }

        /// <summary>
        /// Remove item from cache
        /// </summary>
        /// <param name="key">Name of cached item</param>
        public static void Clear(string key)
        {
            if (HttpContext.Current != null)
            HttpContext.Current.Cache.Remove(key);
        }

        /// <summary>
        /// Check for item in cache
        /// </summary>
        /// <param name="key">Name of cached item</param>
        /// <returns></returns>
        public static bool Exists(string key)
        {
            var exists= HttpContext.Current != null && HttpContext.Current.Cache[key] != null;
            return exists;
        }

        /// <summary>
        /// Retrieve cached item
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="key">Name of cached item</param>
        /// <param name="value">Cached value. Default(T) if
        /// item doesn't exist.</param>
        /// <returns>Cached item as type</returns>
        public static bool Get<T>(string key, out T value)
        {
            try
            {
                if (!Exists(key))
                {
                    value = default(T);
                    return false;
                }

                value = (T)HttpContext.Current.Cache[key];
            }
            catch
            {
                value = default(T);
                return false;
            }

            return true;
        }
    }
}
相关问题