
这里主要讲两个缓存的使用,MemoryCache和Redis
先讲讲常见的缓存
1、.net framework web中自带有Cache缓存,这种缓存属于粘性缓存,是缓存到项目中的,项目从服务器迁移的时候缓存的内容也能够随着服务器一起迁移
2、MemoryCache缓存则需要引用NuGet包 Microsoft.Extensions.Caching.Memory
3、Redis,Redis也有多种,我使用过ServiceStack.Redis和StackExchange.Reids,这两个的区别也是很大的ServiceStack.Redis是商用的,不给钱每个小时的使用是有限的,好像是六千次,但是速度稍微比StackExchange.Reids快一点点,毕竟是收费的,但是StackExchange.Reids没有使用限制,所以这里主要讲一下StackExchange.Reids怎么用
先讲MemoryCache怎么用吧
一、引用Microsoft.Extensions.Caching.Memory NuGet包
二、开写
- private static IMemoryCache _memoryCache = null;
- public Cache()
- {
- _memoryCache = new MemoryCache(new MemoryCacheOptions());
- }
- /// <summary>
- /// 缓存绝对过期时间
- /// </summary>
- ///<param name="key">Cache键值</param>
- ///<param name="value">给Cache[key]赋的值</param>
- ///<param name="minute">minute分钟后绝对过期</param>
- public void CacheInsert(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 void CacheInsertFromMinutes(string key, object value, int minute)
- {
- if (value == null) return;
- _memoryCache.Set(key, value, new MemoryCacheEntryOptions()
- .SetSlidingExpiration(TimeSpan.FromMinutes(minute)));
- }
- /// <summary>
- ///写入缓存
- /// </summary>
- ///<param name="key">Cache键值</param>
- ///<param name="value">给Cache[key]赋的值</param>
- public void CacheInsert(string key, object value)
- {
- _memoryCache.Set(key, value);
- }
- /// <summary>
- ///清除指定缓存
- /// </summary>
- ///<param name="key"></param>
- public void RemoveCache(string key)
- {
- _memoryCache.Remove(key);
- }
- /// <summary>
- ///读取缓存
- /// </summary>
- ///<param name="key"></param>
- public object GetCache(string key)
- {
- return _memoryCache.Get(key);
- }
三、在要使用缓存的项目中的Startup类的ConfigureServices方法注入这个服务
- services.AddSingleton(new CUE.Cache.Cache());

接收这个注入就可以用了,就像这样,完美
- private readonly CUE.Cache.Cache _cache;
-
- public HomeController(CUE.Cache.Cache cache)
- {
- _cache = cache;
- }
- public IActionResult Index()
- {
- _cache.CacheInsert("Key","vaule",10);
- return View();
- }
一、现在用StackExchange.Redis
1,应为我们是把缓存封装到类库里面的,然而类库不能直接读取配置文件,redis又需要稍微配置已下连接地址,所以我有一篇文章讲怎么用类库读取配置文件的,有空可以去看一下
2.先引用StackExchange.Redis NuGet包
二、写配置文件
写到需要使用缓存的项目的appsettings.json里面
- "Redis": {
- "Default": {
- "Connection": "127.0.0.1:6379",
- "InstanceName": "local",
- "DefaultDB": 8
- }
- }
三、读取配置文件
- public class RedisConfigInfo
- {
- /// <summary>
- /// 读取Redis:Default 配置文件
- /// </summary>
- /// <returns></returns>
- public static IConfigurationSection GetConfig()
- {
- return ConfigHelper.GetSection("Redis:Default");
- }
- /// <summary>
- /// 读取Redis:Default下指定的值
- /// </summary>
- /// <param name="Key"></param>
- /// <returns></returns>
- public static string GetConfigValue(string Key)
- {
- return GetConfig().GetSection(Key).Value;
- }
- }
三、写连接字符串
- public class RedisCathe
- {
- //连接字符串
- private string _connectionString;
- //实例名称
- private string _instanceName;
- //数据库
- private int _defaultDB;
- private ConcurrentDictionary<string, ConnectionMultiplexer> _connections;
- public RedisCathe()
- {
- _connectionString = RedisConfigInfo.GetConfigValue("Connection");
- _instanceName = RedisConfigInfo.GetConfigValue("InstanceName");
- //给定默认数据库,默认为0
- _defaultDB = int.Parse(RedisConfigInfo.GetConfigValue("DefaultDB") ?? "0");
- _connections = new ConcurrentDictionary<string, ConnectionMultiplexer>();
- }
-
- /// <summary>
- /// 获取ConnectionMultiplexer
- /// </summary>
- /// <returns></returns>
- private ConnectionMultiplexer GetConnect()
- {
- return _connections.GetOrAdd(_instanceName, p => ConnectionMultiplexer.Connect(_connectionString));
- }
-
- /// <summary>
- /// 获取数据库
- /// </summary>
- /// <param name="configName"></param>
- /// <param name="db">默认为0:优先代码的db配置,其次config中的配置</param>
- /// <returns></returns>
- public IDatabase GetDatabase()
- {
- return GetConnect().GetDatabase(_defaultDB);
- }
-
- public IServer GetServer(string configName = null, int endPointsIndex = 0)
- {
- var confOption = ConfigurationOptions.Parse(_connectionString);
- return GetConnect().GetServer(confOption.EndPoints[endPointsIndex]);
- }
-
- public ISubscriber GetSubscriber(string configName = null)
- {
- return GetConnect().GetSubscriber();
- }
-
- public void Dispose()
- {
- if (_connections != null && _connections.Count > 0)
- {
- foreach (var item in _connections.Values)
- {
- item.Close();
- }
- }
- }
- }
三、封装方法
- public class Cache
- {
- private readonly IDatabase _redis;
- public Cache()
- {
- _redis = new RedisCathe().GetDatabase();
- }
- /// <summary>
- ///写入缓存
- /// </summary>
- ///<param name="key">Cache键值</param>
- ///<param name="value">给Cache[key]赋的值</param>
- public void CacheInsert(string key, string value)
- {
- _redis.StringSet(key, value);
- }
-
- /// <summary>
- /// 缓存过期时间
- /// </summary>
- ///<param name="key">Cache键值</param>
- ///<param name="value">给Cache[key]赋的值</param>
- ///<param name="minute">minute分钟后绝对过期</param>
- public void CacheInsert(string key, string value, int minute)
- {
- _redis.StringSet(key, value, TimeSpan.FromMinutes(minute));
- }
- /// <summary>
- ///读取缓存
- /// </summary>
- ///<param name="key"></param>
- public string GetCache(string key)
- {
- return _redis.StringGet(key);
- }
-
- /// <summary>
- ///清除指定缓存
- /// </summary>
- ///<param name="key"></param>
- public void RemoveCache(string key)
- {
- _redis.KeyDelete(key);
- }
- }
四、用法就和上面的Cache一模一样,先注入,然后直接用就行了
Good
评价
饰心
我记得MemoryCache缓存如果项目发布到IIS的话 会因为IIS有自动回收机制,导致缓存只有20分钟时效