封装一个MemoryCacheUtil用于程序内缓存
在 .Net 中,如果想缓存少量数据又避免维护一个 Redis,System.Runtime.Caching.MemoryCache 是一个不错的选择。封装了一个工具类,用来处理缓存的增、改、查。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;
namespace Naylor.common
{
internal class MemoryCacheUtil
{
/// <summary>
/// 创建 - 永不过期
/// </summary>
/// <param name="key">缓存键,不可重复。若出现重复,不会覆盖。</param>
/// <param name="value">缓存值</param>
/// <param name="region">区域,用于分组一批key</param>
/// <returns></returns>
internal static bool CreateForever<T>(string key, T value)
{
return MemoryCache.Default.Add(new CacheItem(key, value), new CacheItemPolicy() { Priority = CacheItemPriority.NotRemovable });
}
/// <summary>
/// 创建或更新 - 永不过期
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
internal static void CreateOrUpdateForever<T>(string key, T value)
{
MemoryCache.Default.Set(new CacheItem(key, value), new CacheItemPolicy() { Priority = CacheItemPriority.NotRemovable });
}
/// <summary>
/// 更新
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">缓存键</param>
/// <param name="value">缓存值</param>
/// <param name="createSuccess">创建是否成功</param>
/// <param name="autoCreate">若没有是否自动创建,默认为 true </param>
internal static void Update<T>(string key, T value, out bool createSuccess, bool autoCreate = true)
{
bool _createSuccess = false;
if (MemoryCache.Default.Contains(key))
{
MemoryCache.Default.Set(new CacheItem(key, value), new CacheItemPolicy() { Priority = CacheItemPriority.NotRemovable });
}
else
{
if (autoCreate)
{
_createSuccess = CreateForever(key, value);
}
}
createSuccess = _createSuccess;
}
/// <summary>
/// 查询 - 根据keys
/// </summary>
/// <param name="keys">缓存键</param>
/// <returns></returns>
internal static Dictionary<string, object> findByKey<T>(HashSet<string> keys)
{
return (Dictionary<string, object>)MemoryCache.Default.GetValues(keys);
}
/// <summary>
/// 获取 - 根据key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
internal static T getByKey<T>(string key)
{
return (T)MemoryCache.Default.Get(key);
}
}
}
其中需要注意:
* create方法不会像redis那样覆盖,先到先得,后面的将无法插入
* MemoryCache没有真正意义上的更新接口,使用set方式实现,set和add的区别在于,set会出现脏读情况 还没试,收藏下 最近在优化内存,试下。
页:
[1]