memory cache

C# Memroy cache 缓存使用
最近也是离职了。没有找到合适的工作。闲着也是闲着。然后就学习了一下memory cache。缓存的优点有很多。他减少了对数据库的压力。使得不需要总是去访问数据库去查询。直接从缓存中读取数据

用例

这边我也是写了一个简单的控制台应用程序。
string json = File.ReadAllText(“D:\项目\Memroy Cache文件\Test1\ConsoleApp1\ConsoleApp2\userinfo.text”);//读取json文件

        JavaScriptSerializer jss = new JavaScriptSerializer();
        var user = ModelAndJSonHelper<userInfo>.JSonToModelList(json);//将JSon格式的数据实体转化成JSonToModelList
        List<userInfo> userinfolist = new List<userInfo>();//建立一个数组用来保存数据,测试用的
        foreach (var item in user)//循环遍历看看数据有没有
        {
            Console.WriteLine(item.name+"  ,"+item.age+" ,"+item.idCard);
            userinfolist.Add(item);//将数据保存到数组中
           
        }
        var query = userinfolist.FindAll(x => true);//模拟查询数据
        CacheHelp.CacheInsert("12",query);//将查询到的数据保存到memroy cache 缓存中
        var s = CacheHelp.CacheValue("12")as List<userInfo>;//根据key获取缓存中的value值


        foreach (var items in s)//循环遍历缓存中得到的值
        {
            Console.WriteLine(items.name);
        }
        CacheHelp.CacheNull("12");//清除缓存中的key
      
        Console.ReadKey();

帮助类

/// 将JSon格式的数据实体转化成JSonToModelList
///
///
///
public static List JSonToModelList(string json)
{
try
{
if (string.IsNullOrEmpty(json))
return null;
var firstStr = json.Trim().Substring(0, 2);
List tList = null;
if (firstStr.Contains("["))
{
tList = (List)JSonHelper.Decode(json, typeof(List));
}
return tList;
}
catch
{
return null;
}
}
public static object Decode(string json, Type type)
{
return JsonConvert.DeserializeObject(json, type);
}

缓存帮助类,该帮助类来自b站罗分明

地址:http://www.luofenming.com/show.aspx?id=ART2019101900001

public class CacheHelp
{
public static IMemoryCache _memoryCache = new MemoryCache(new MemoryCacheOptions());

    /// <summary>
    /// 缓存绝对过期时间
    /// </summary>
    ///<param name="key">Cache键值</param>
    ///<param name="value">给Cache[key]赋的值</param>
    ///<param name="minute">minute分钟后绝对过期</param>
    public static void CacheInsertAddMinutes(string key, object value, int minute)
    {
        if (value == null) return;
        _memoryCache.Set(key, value, new MemoryCacheEntryOptions()
                .SetAbsoluteExpiration(TimeSpan.FromMinutes(minute)));
    }


    /// <summary>
    /// 缓存相对过期,最后一次访问后minute分钟后过期
    /// </summary>
    ///<param name="key">Cache键值</param>
    ///<param name="value">给Cache[key]赋的值</param>
    ///<param name="minute">滑动过期分钟</param>
    public static void CacheInsertFromMinutes(string key, object value, int minute)
    {
        if (value == null) return;
        _memoryCache.Set(key, value, new MemoryCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromMinutes(minute)));
    }


    /// <summary>
    ///以key键值,把value赋给Cache[key].如果不主动清空,会一直保存在内存中.
    /// </summary>
    ///<param name="key">Cache键值</param>
    ///<param name="value">给Cache[key]赋的值</param>
    public static void CacheInsert(string key, object value)
    {
        _memoryCache.Set(key, value);
    }

    /// <summary>
    ///清除Cache[key]的值
    /// </summary>
    ///<param name="key"></param>
    public static void CacheNull(string key)
    {
        _memoryCache.Remove(key);
    }

    /// <summary>
    ///根据key值,返回Cache[key]的值
    /// </summary>
    ///<param name="key"></param>
    public static object CacheValue(string key)
    {
        return _memoryCache.Get(key);
    }
}

**运行结果
张三 ,15 ,10086
张三2 ,16 ,100861
张三3 ,17 ,1008611
张三
张三2
张三3
**

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C# MemoryCache is a caching mechanism provided by the .NET Framework that allows developers to store data in memory for faster access. It is a key-value store where data is stored as key-value pairs and can be accessed using the key. MemoryCache is designed to be used in applications that require frequent access to data, such as web applications that need to retrieve data from a database repeatedly. By storing frequently accessed data in MemoryCache, you can reduce the number of database calls and improve the performance of your application. MemoryCache provides several features, such as time-based expiration, sliding expiration, and the ability to remove items from the cache manually. It also provides thread-safe operations to prevent race conditions when multiple threads access the cache simultaneously. To use MemoryCache in your C# application, you can create an instance of the MemoryCache class and add items to the cache using the Add method. You can also retrieve items from the cache using the Get method and remove items from the cache using the Remove method. Here's an example of how to use MemoryCache in C#: ``` // Create a new instance of the MemoryCache class MemoryCache cache = MemoryCache.Default; // Add an item to the cache with a key of "myKey" and a value of "myValue" cache.Add("myKey", "myValue", DateTimeOffset.Now.AddMinutes(5)); // Retrieve the value of the item with a key of "myKey" string value = cache.Get("myKey") as string; // Remove the item from the cache with a key of "myKey" cache.Remove("myKey"); ``` Overall, MemoryCache is a powerful tool for improving the performance of your C# applications by reducing the number of database calls and providing faster access to frequently accessed data.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值