Asp.net Core 缓存 MemoryCache 和 Redis
Asp.net Core 缓存 MemoryCache 和 Redis
目录索引
简介
经过 N 久反复的尝试,翻阅了网上无数的资料,GitHub上下载了十几个源码参考, Memory 和 Redis 终于写出一个 简陋 的 封装,为了统一和易用,我们两种缓存都统一实现了一个接口 ICacheService,微软也有很多是通过IDistributedCache,大家可以参考 https://docs.asp.net/en/latest/performance/caching/distributed.html ,GitHub上也有很多很好的封装,这里我们就不一一介绍了,大家自行参考,现在搞 Asp.net Core的还是不是很多,中文的资料也少的可怜,而且基本都是千篇一律照搬,对于只认识 ABCDEFG的我来说,过程是十分艰辛的,一篇文章往往要看四五遍,逐行逐句翻译,说多了都是泪,不说了,我们开始。期间,得到了很多朋友的帮助,在此表示感谢!
缓存接口 ICacheService
缓存也好,数据库也好,我们就是进行CRUD操作,接口没什么好解释的,注释我写的很明白,这里就列给大家:
# 验证缓存项是否存在

1 /// <summary>
2 /// 验证缓存项是否存在
3 /// </summary>
4 /// <param name="key">缓存Key</param>
5 /// <returns></returns>
6 bool Exists(string key);
7
8 /// <summary>
9 /// 验证缓存项是否存在(异步方式)
10 /// </summary>
11 /// <param name="key">缓存Key</param>
12 /// <returns></returns>
13 Task<bool> ExistsAsync(string key);

# 添加缓存

1 /// <summary>
2 /// 添加缓存
3 /// </summary>
4 /// <param name="key">缓存Key</param>
5 /// <param name="value">缓存Value</param>
6 /// <returns></returns>
7 bool Add(string key, object value);
8
9 /// <summary>
10 /// 添加缓存(异步方式)
11 /// </summary>
12 /// <param name="key">缓存Key</param>
13 /// <param name="value">缓存Value</param>
14 /// <returns></returns>
15 Task<bool> AddAsync(string key, object value);
16
17 /// <summary>
18 /// 添加缓存
19 /// </summary>
20 /// <param name="key">缓存Key</param>
21 /// <param name="value">缓存Value</param>
22 /// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
23 /// <param name="expiressAbsoulte">绝对过期时长</param>
24 /// <returns></returns>
25 bool Add(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte);
26
27 /// <summary>
28 /// 添加缓存(异步方式)
29 /// </summary>
30 /// <param name="key">缓存Key</param>
31 /// <param name="value">缓存Value</param>
32 /// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
33 /// <param name="expiressAbsoulte">绝对过期时长</param>
34 /// <returns></returns>
35 Task<bool> AddAsync(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte);
36
37 /// <summary>
38 /// 添加缓存
39 /// </summary>
40 /// <param name="key">缓存Key</param>
41 /// <param name="value">缓存Value</param>
42 /// <param name="expiresIn">缓存时长</param>
43 /// <param name="isSliding">是否滑动过期(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
44 /// <returns></returns>
45 bool Add(string key, object value, TimeSpan expiresIn, bool isSliding = false);
46
47 /// <summary>
48 /// 添加缓存(异步方式)
49 /// </summary>
50 /// <param name="key">缓存Key</param>
51 /// <param name="value">缓存Value</param>
52 /// <param name="expiresIn">缓存时长</param>
53 /// <param name="isSliding">是否滑动过期(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
54 /// <returns></returns>
55 Task<bool> AddAsync(string key, object value, TimeSpan expiresIn, bool isSliding = false);

# 删除缓存

1 /// <summary>
2 /// 删除缓存
3 /// </summary>
4 /// <param name="key">缓存Key</param>
5 /// <returns></returns>
6 bool Remove(string key);
7
8 /// <summary>
9 /// 删除缓存(异步方式)
10 /// </summary>
11 /// <param name="key">缓存Key</param>
12 /// <returns></returns>
13 Task<bool> RemoveAsync(string key);
14
15 /// <summary>
16 /// 批量删除缓存
17 /// </summary>
18 /// <param name="key">缓存Key集合</param>
19 /// <returns></returns>
20 void RemoveAll(IEnumerable<string> keys);
21
22 /// <summary>
23 /// 批量删除缓存(异步方式)
24 /// </summary>
25 /// <param name="key">缓存Key集合</param>
26 /// <returns></returns>
27 Task RemoveAllAsync(IEnumerable<string> keys);

# 获取缓存

1 /// <summary>
2 /// 获取缓存
3 /// </summary>
4 /// <param name="key">缓存Key</param>
5 /// <returns></returns>
6 T Get<T>(string key) where T : class;
7
8 /// <summary>
9 /// 获取缓存(异步方式)
10 /// </summary>
11 /// <param name="key">缓存Key</param>
12 /// <returns></returns>
13 Task<T> GetAsync<T>(string key) where T : class;
14
15 /// <summary>
16 /// 获取缓存
17 /// </summary>
18 /// <param name="key">缓存Key</param>
19 /// <returns></returns>
20 object Get(string key);
21
22 /// <summary>
23 /// 获取缓存(异步方式)
24 /// </summary>
25 /// <param name="key">缓存Key</param>
26 /// <returns></returns>
27 Task<object> GetAsync(string key);
28
29 /// <summary>
30 /// 获取缓存集合
31 /// </summary>
32 /// <param name="keys">缓存Key集合</param>
33 /// <returns></returns>
34 IDictionary<string, object> GetAll(IEnumerable<string> keys);
35
36 /// <summary>
37 /// 获取缓存集合(异步方式)
38 /// </summary>
39 /// <param name="keys">缓存Key集合</param>
40 /// <returns></returns>
41 Task<IDictionary<string, object>> GetAllAsync(IEnumerable<string> keys);

# 修改缓存

1 /// <summary>
2 /// 修改缓存
3 /// </summary>
4 /// <param name="key">缓存Key</param>
5 /// <param name="value">新的缓存Value</param>
6 /// <returns></returns>
7 bool Replace(string key, object value);
8
9 /// <summary>
10 /// 修改缓存(异步方式)
11 /// </summary>
12 /// <param name="key">缓存Key</param>
13 /// <param name="value">新的缓存Value</param>
14 /// <returns></returns>
15 Task<bool> ReplaceAsync(string key, object value);
16
17 /// <summary>
18 /// 修改缓存
19 /// </summary>
20 /// <param name="key">缓存Key</param>
21 /// <param name="value">新的缓存Value</param>
22 /// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
23 /// <param name="expiressAbsoulte">绝对过期时长</param>
24 /// <returns></returns>
25 bool Replace(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte);
26
27 /// <summary>
28 /// 修改缓存(异步方式)
29 /// </summary>
30 /// <param name="key">缓存Key</param>
31 /// <param name="value">新的缓存Value</param>
32 /// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
33 /// <param name="expiressAbsoulte">绝对过期时长</param>
34 /// <returns></returns>
35 Task<bool> ReplaceAsync(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte);
36
37 /// <summary>
38 /// 修改缓存
39 /// </summary>
40 /// <param name="key">缓存Key</param>
41 /// <param name="value">新的缓存Value</param>
42 /// <param name="expiresIn">缓存时长</param>
43 /// <param name="isSliding">是否滑动过期(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
44 /// <returns></returns>
45 bool Replace(string key, object value, TimeSpan expiresIn, bool isSliding = false);
46
47 /// <summary>
48 /// 修改缓存(异步方式)
49 /// </summary>
50 /// <param name="key">缓存Key</param>
51 /// <param name="value">新的缓存Value</param>
52 /// <param name="expiresIn">缓存时长</param>
53 /// <param name="isSliding">是否滑动过期(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
54 /// <returns></returns>
55 Task<bool> ReplaceAsync(string key, object value, TimeSpan expiresIn, bool isSliding = false);

缓存实现类 MemoryCache
MemoryCache 这个比较简单,有微软比较完善的文档和一些比较好的文章,这个大家都用好久了。
我们新建一个缓存实现类 MemoryCacheService 实现接口 ICacheService
public class MemoryCacheService :ICacheService { }
通过构造器注入 IMemoryCache:
protected IMemoryCache _cache;
public MemoryCacheService(IMemoryCache cache)
{
_cache = cache;
}
实现接口的方法,我们的方法都带有 异步 和 同步 两种,我们节约篇章和时间,异步的就不大家写了,大家自己添加一下就好。
# 验证缓存项是否存在
在MemoryCache中,我们是通过 TryGetValue 来检测 Key是否存在的

1 /// <summary>
2 /// 验证缓存项是否存在
3 /// </summary>
4 /// <param name="key">缓存Key</param>
5 /// <returns></returns>
6 public bool Exists(string key)
7 {
8 if (key == null)
9 {
10 throw new ArgumentNullException(nameof(key));
11 }
12 object cached;
13 return _cache.TryGetValue(key,out cached);
14 }

# 添加缓存
三个添加方法 :

1 /// <summary>
2 /// 添加缓存
3 /// </summary>
4 /// <param name="key">缓存Key</param>
5 /// <param name="value">缓存Value</param>
6 /// <returns></returns>
7 public bool Add(string key, object value)
8 {
9 if (key == null)
10 {
11 throw new ArgumentNullException(nameof(key));
12 }
13 if (value == null)
14 {
15 throw new ArgumentNullException(nameof(value));
16 }
17 _cache.Set(key, value);
18 return Exists(key);
19 }
20 /// <summary>
21 /// 添加缓存
22 /// </summary>
23 /// <param name="key">缓存Key</param>
24 /// <param name="value">缓存Value</param>
25 /// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
26 /// <param name="expiressAbsoulte">绝对过期时长</param>
27 /// <returns></returns>
28 public bool Add(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte)
29 {
30 if (key == null)
31 {
32 throw new ArgumentNullException(nameof(key));
33 }
34 if (value == null)
35 {
36 throw new ArgumentNullException(nameof(value));
37 }
38 _cache.Set(key, value,
39 new MemoryCacheEntryOptions()
40 .SetSlidingExpiration(expiresSliding)
41 .SetAbsoluteExpiration(expiressAbsoulte)
42 );
43
44 return Exists(key);
45 }
46 /// <summary>
47 /// 添加缓存
48 /// </summary>
49 /// <param name="key">缓存Key</param>
50 /// <param name="value">缓存Value</param>
51 /// <param name="expiresIn">缓存时长</param>
52 /// <param name="isSliding">是否滑动过期(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
53 /// <returns></returns>
54 public bool Add(string key, object value, TimeSpan expiresIn,bool isSliding = false)
55 {
56 if (key == null)
57 {
58 throw new ArgumentNullException(nameof(key));
59 }
60 if (value == null)
61 {
62 throw new ArgumentNullException(nameof(value));
63 }
64 if (isSliding)
65 _cache.Set(key, value,
66 new MemoryCacheEntryOptions()
67 .SetSlidingExpiration(expiresIn)
68 );
69 else
70 _cache.Set(key, value,
71 new MemoryCacheEntryOptions()
72 .SetAbsoluteExpiration(expiresIn)
73 );
74
75 return Exists(key);
76 }

# 删除缓存
单个删除 和 批量删除

1 /// <summary>
2 /// 删除缓存
3 /// </summary>
4 /// <param name="key">缓存Key</param>
5 /// <returns></returns>
6 public bool Remove(string key)
7 {
8 if (key == null)
9 {
10 throw new ArgumentNullException(nameof(key));
11 }
12 _cache.Remove(key);
13
14 return !Exists(key);
15 }
16 /// <summary>
17 /// 批量删除缓存
18 /// </summary>
19 /// <param name="key">缓存Key集合</param>
20 /// <returns></returns>
21 public void RemoveAll(IEnumerable<string> keys)
22 {
23 if (keys == null)
24 {
25 throw new ArgumentNullException(nameof(keys));
26 }
27
28 keys.ToList().ForEach(item => _cache.Remove(item));
29 }

# 获取缓存

1 /// <summary>
2 /// 获取缓存
3 /// </summary>
4 /// <param name="key">缓存Key</param>
5 /// <returns></returns>
6 public T Get<T>(string key) where T : class
7 {
8 if (key == null)
9 {
10 throw new ArgumentNullException(nameof(key));
11 }
12 return _cache.Get(key) as T;
13 }
14 /// <summary>
15 /// 获取缓存
16 /// </summary>
17 /// <param name="key">缓存Key</param>
18 /// <returns></returns>
19 public object Get(string key)
20 {
21 if (key == null)
22 {
23 throw new ArgumentNullException(nameof(key));
24 }
25 return _cache.Get(key);
26 }
27 /// <summary>
28 /// 获取缓存集合
29 /// </summary>
30 /// <param name="keys">缓存Key集合</param>
31 /// <returns></returns>
32 public IDictionary<string, object> GetAll(IEnumerable<string> keys)
33 {
34 if (keys == null)
35 {
36 throw new ArgumentNullException(nameof(keys));
37 }
38
39 var dict = new Dictionary<string, object>();
40
41 keys.ToList().ForEach(item => dict.Add(item, _cache.Get(item)));
42
43 return dict;
44 }

# 修改缓存

1 /// <summary>
2 /// 修改缓存
3 /// </summary>
4 /// <param name="key">缓存Key</param>
5 /// <param name="value">新的缓存Value</param>
6 /// <returns></returns>
7 public bool Replace(string key, object value)
8 {
9 if (key == null)
10 {
11 throw new ArgumentNullException(nameof(key));
12 }
13 if (value == null)
14 {
15 throw new ArgumentNullException(nameof(value));
16 }
17 if (Exists(key))
18 if (!Remove(key)) return false;
19
20 return Add(key, value);
21
22 }
23 /// <summary>
24 /// 修改缓存
25 /// </summary>
26 /// <param name="key">缓存Key</param>
27 /// <param name="value">新的缓存Value</param>
28 /// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
29 /// <param name="expiressAbsoulte">绝对过期时长</param>
30 /// <returns></returns>
31 public bool Replace(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte)
32 {
33 if (key == null)
34 {
35 throw new ArgumentNullException(nameof(key));
36 }
37 if (value == null)
38 {
39 throw new ArgumentNullException(nameof(value));
40 }
41 if (Exists(key))
42 if (!Remove(key)) return false;
43
44 return Add(key, value, expiresSliding, expiressAbsoulte);
45 }
46 /// <summary>
47 /// 修改缓存
48 /// </summary>
49 /// <param name="key">缓存Key</param>
50 /// <param name="value">新的缓存Value</param>
51 /// <param name="expiresIn">缓存时长</param>
52 /// <param name="isSliding">是否滑动过期(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
53 /// <returns></returns>
54 public bool Replace(string key, object value, TimeSpan expiresIn, bool isSliding = false)
55 {
56 if (key == null)
57 {
58 throw new ArgumentNullException(nameof(key));
59 }
60 if (value == null)
61 {
62 throw new ArgumentNullException(nameof(value));
63 }
64 if (Exists(key))
65 if (!Remove(key)) return false;
66
67 return Add(key, value, expiresIn, isSliding);
68 }

最后 释放:
public void Dispose()
{
if (_cache != null)
_cache.Dispose();
GC.SuppressFinalize(this);
}
缓存实现类 Redis
Redis一般都是运行的Liunx的,我们在 【(第十章)】发布项目到 Linux 上运行 Core 项目 中介绍了,如何在Linux上开发运行Core项目,当然,我相信,很多朋友还是在 Windows 上做开发、测试的,这里给大家一个windows 上的Redis和管理软件,如果没有或者不知道怎么找的朋友可以下载下来,在windows上测试 Redis :连接可能失效 百度网盘 提取码:uglb 百度网盘 提取码:gl0e
安装第一个后,启动Redis服务就行了,管理软件的界面也很简洁
我们先来看我们的 RedisCacheService:
为了统一管理和切换使用,我们的 RedisCacheService 同样实现接口 ICacheService
public class RedisCacheService : ICacheService { }
同样,我们通过构造器注入:
protected IDatabase _cache;
private ConnectionMultiplexer _connection;
private readonly string _instance;
public RedisCacheService(RedisCacheOptions options, int database = 0)
{
_connection = ConnectionMultiplexer.Connect(options.Configuration);
_cache = _connection.GetDatabase(database);
_instance = options.InstanceName;
}
说明一下:我们需要添加一个Redis包:Microsoft.Extensions.Caching.Redis,这是官方的,但是不知道是我程序的原因还是什么原因,总是还原失败,命令强行还原包也不行,所以 我用的是移植的包: Microsoft.Extensions.Caching.Redis.Core,如果你们可以,最好还是用官方的包。
这里我们写了个方法,来组合Key值和实例名,就是Key值转为 实例名+Key
public string GetKeyForRedis(string key)
{
return _instance + key;
}
# 验证缓存项是否存在

1 /// <summary>
2 /// 验证缓存项是否存在
3 /// </summary>
4 /// <param name="key">缓存Key</param>
5 /// <returns></returns>
6 public bool Exists(string key)
7 {
8 if (key == null)
9 {
10 throw new ArgumentNullException(nameof(key));
11 }
12 return _cache.KeyExists(GetKeyForRedis(key));
13 }

# 添加缓存
注意:我翻阅了很多资料,没有找到Redis支持滑动和绝对过期,但是都是继承的统一接口,所以这里添加方法 滑动过期时没有用的。

1 /// <summary>
2 /// 添加缓存
3 /// </summary>
4 /// <param name="key">缓存Key</param>
5 /// <param name="value">缓存Value</param>
6 /// <returns></returns>
7 public bool Add(string key, object value)
8 {
9 if (key == null)
10 {
11 throw new ArgumentNullException(nameof(key));
12 }
13 return _cache.StringSet(GetKeyForRedis(key), Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value)));
14 }
15 /// <summary>
16 /// 添加缓存
17 /// </summary>
18 /// <param name="key">缓存Key</param>
19 /// <param name="value">缓存Value</param>
20 /// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间,Redis中无效)</param>
21 /// <param name="expiressAbsoulte">绝对过期时长</param>
22 /// <returns></returns>
23 public bool Add(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte)
24 {
25 if (key == null)
26 {
27 throw new ArgumentNullException(nameof(key));
28 }
29 return _cache.StringSet(GetKeyForRedis(key), Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value)),expiressAbsoulte);
30 }
31 /// <summary>
32 /// 添加缓存
33 /// </summary>
34 /// <param name="key">缓存Key</param>
35 /// <param name="value">缓存Value</param>
36 /// <param name="expiresIn">缓存时长</param>
37 /// <param name="isSliding">是否滑动过期(如果在过期时间内有操作,则以当前时间点延长过期时间,Redis中无效)</param>
38 /// <returns></returns>
39 public bool Add(string key, object value, TimeSpan expiresIn, bool isSliding = false)
40 {
41 if (key == null)
42 {
43 throw new ArgumentNullException(nameof(key));
44 }
45
46
47 return _cache.StringSet(GetKeyForRedis(key), Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value)), expiresIn);
48 }

# 删除缓存

1 /// <summary>
2 /// 删除缓存
3 /// </summary>
4 /// <param name="key">缓存Key</param>
5 /// <returns></returns>
6 public bool Remove(string key)
7 {
8 if (key == null)
9 {
10 throw new ArgumentNullException(nameof(key));
11 }
12 return _cache.KeyDelete(GetKeyForRedis(key));
13 }
14 /// <summary>
15 /// 批量删除缓存
16 /// </summary>
17 /// <param name="key">缓存Key集合</param>
18 /// <returns></returns>
19 public void RemoveAll(IEnumerable<string> keys)
20 {
21 if (keys == null)
22 {
23 throw new ArgumentNullException(nameof(keys));
24 }
25
26 keys.ToList().ForEach(item => Remove(GetKeyForRedis(item)));
27 }

# 获取缓存

1 /// <summary>
2 /// 获取缓存
3 /// </summary>
4 /// <param name="key">缓存Key</param>
5 /// <returns></returns>
6 public T Get<T>(string key) where T : class
7 {
8 if (key == null)
9 {
10 throw new ArgumentNullException(nameof(key));
11 }
12
13 var value = _cache.StringGet(GetKeyForRedis(key));
14
15 if (!value.HasValue)
16 {
17 return default(T);
18 }
19
20 return JsonConvert.DeserializeObject<T>(value);
21 }
22 /// <summary>
23 /// 获取缓存
24 /// </summary>
25 /// <param name="key">缓存Key</param>
26 /// <returns></returns>
27 public object Get(string key)
28 {
29 if (key == null)
30 {
31 throw new ArgumentNullException(nameof(key));
32 }
33
34 var value = _cache.StringGet(GetKeyForRedis(key));
35
36 if(!value.HasValue)
37 {
38 return null;
39 }
40 /// <summary>
41 /// 获取缓存集合
42 /// </summary>
43 /// <param name="keys">缓存Key集合</param>
44 /// <returns></returns>
45 public IDictionary<string, object> GetAll(IEnumerable<string> keys)
46 {
47 if (keys == null)
48 {
49 throw new ArgumentNullException(nameof(keys));
50 }
51 var dict = new Dictionary<string, object>();
52
53 keys.ToList().ForEach(item => dict.Add(item, Get(GetKeyForRedis(item))));
54
55 return dict;
56 }
57
58 return JsonConvert.DeserializeObject(value);
59 }

# 修改缓存

1 /// <summary>
2 /// 修改缓存
3 /// </summary>
4 /// <param name="key">缓存Key</param>
5 /// <param name="value">新的缓存Value</param>
6 /// <returns></returns>
7 public bool Replace(string key, object value)
8 {
9 if (key == null)
10 {
11 throw new ArgumentNullException(nameof(key));
12 }
13
14 if(Exists(key))
15 if (!Remove(key))
16 return false;
17
18 return Add(key, value);
19
20 }
21 /// <summary>
22 /// 修改缓存
23 /// </summary>
24 /// <param name="key">缓存Key</param>
25 /// <param name="value">新的缓存Value</param>
26 /// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
27 /// <param name="expiressAbsoulte">绝对过期时长</param>
28 /// <returns></returns>
29 public bool Replace(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte)
30 {
31 if (key == null)
32 {
33 throw new ArgumentNullException(nameof(key));
34 }
35
36 if (Exists(key))
37 if (!Remove(key))
38 return false;
39
40 return Add(key, value, expiresSliding, expiressAbsoulte);
41 }
42 /// <summary>
43 /// 修改缓存
44 /// </summary>
45 /// <param name="key">缓存Key</param>
46 /// <param name="value">新的缓存Value</param>
47 /// <param name="expiresIn">缓存时长</param>
48 /// <param name="isSliding">是否滑动过期(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
49 /// <returns></returns>
50 public bool Replace(string key, object value, TimeSpan expiresIn, bool isSliding = false)
51 {
52 if (key == null)
53 {
54 throw new ArgumentNullException(nameof(key));
55 }
56
57 if (Exists(key))
58 if (!Remove(key)) return false;
59
60 return Add(key, value, expiresIn, isSliding);
61 }

同样,释放:
public void Dispose()
{
if (_connection != null)
_connection.Dispose();
GC.SuppressFinalize(this);
}
Startup.cs 和 缓存配置
我们在 【(第八章)】读取配置文件(二) 读取自定义配置文件 中讲到了如何读取自定义配置文件,同样,我们把缓存的配置 也放在 我们的自定义配置文件siteconfig.json中:
我们写一个类,来获取配置几个配置:
CacheProvider: _isUseRedis --- 是否使用Redis
_connectionString --- Redis连接
_instanceName ---Redis实例名称
在 Startup.cs 的 ConfigureServices(IServiceCollection services) 中:
首先添加:services.AddMemoryCache();
判断是否使用Redis,如果不使用 Redis就默认使用 MemoryCache:
if (_cacheProvider._isUseRedis)
{
//Use Redis
services.AddSingleton(typeof(ICacheService), new RedisCacheService(new RedisCacheOptions
{
Configuration = _cacheProvider._connectionString,
InstanceName = _cacheProvider._instanceName
},0));
}
else
{
//Use MemoryCache
services.AddSingleton<IMemoryCache>(factory =>
{
var cache = new MemoryCache(new MemoryCacheOptions());
return cache;
});
services.AddSingleton<ICacheService, MemoryCacheService>();
}
OK,完成了,因为也是研究Core不到一个月,所以这里面肯定会有些地方写的不好,希望大家指出来,如果有更高的方案或者方法,也麻烦告知一声,在此表示感谢!
希望跟大家一起学习Asp.net Core
Asp.net Core 缓存 MemoryCache 和 Redis的更多相关文章
- 【无私分享:ASP.NET CORE 项目实战(第十一章)】Asp.net Core 缓存 MemoryCache 和 Redis
目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 经过 N 久反复的尝试,翻阅了网上无数的资料,GitHub上下载了十几个源码参考, Memory 和 Redis 终于写出一个 ...
- Redis 入门与 ASP.NET Core 缓存
目录 基础 Redis 库 连接 Redis 能用 redis 干啥 Redis 数据库存储 字符串 订阅发布 RedisValue ASP.NET Core 缓存与分布式缓存 内存中的缓存 ASP. ...
- Asp.net Core2.0 缓存 MemoryCache 和 Redis
自从使用Asp.net Core2.0 以来,不停摸索,查阅资料,这方面的资料是真的少,因此,在前人的基础上,摸索出了Asp.net Core2.0 缓存 MemoryCache 和 Redis的用法 ...
- ASP.NET Core 缓存技术 及 Nginx 缓存配置
前言 在Asp.Net Core Nginx部署一文中,主要是讲述的如何利用Nginx来实现应用程序的部署,使用Nginx来部署主要有两大好处,第一是利用Nginx的负载均衡功能,第二是使用Nginx ...
- asp.net core 缓存和Session
缓存 缓存在内存中 ASP.NET Core 使用 IMemoryCache内存中缓存是使用依赖关系注入从应用中引用的服务. 请在ConfigureServices中调用AddMemoryCache( ...
- ASP.NET Core缓存静态资源
背景 缓存样式表,JavaScript或图像文件等静态资源可以提高您网站的性能.在客户端,总是从缓存中加载一个静态文件,这样可以减少对服务器的请求数量,从而减少获取页面及其资源的时间.在服务器端,由于 ...
- Asp.Net Core 缓存的使用(译)
原文:http://www.binaryintellect.net/articles/a7d9edfd-1f86-45f8-a668-64cc86d8e248.aspx环境:Visual Studio ...
- 【NET Core】 缓存 MemoryCache 和 Redis
缓存接口 ICacheService using System; using System.Collections.Generic; using System.Threading.Tasks; nam ...
- asp.net core上使用Redis demo
整体思路:(1.面向接口编程 2.Redis可视化操作IDE 3.Redis服务) [无私分享:ASP.NET CORE 项目实战(第十一章)]Asp.net Core 缓存 MemoryCache ...
随机推荐
- [转载]监控 Linux 性能的 18 个命令行工具
转自:http://www.kuqin.com/shuoit/20140219/338066.html 对于系统和网络管理员来说每天监控和调试Linux系统的性能问题是一项繁重的工作.在IT领域作为一 ...
- 用UBOOT自带loadb命令加载应用程序到SDRAM中运行的方法
S3C44B0开发板中,用UBOOT自带loadb命令加载应用程序到SDRAM中运行的方法 1.开发板说明: 开发板上已有移植好的UBOOT运行. 2.交叉编译工具链为arm-linu-g ...
- <Win32_8>由浅入深——滚动条
滚动条在Win32程序中是非常常见的一个控件,它的功能和地位也就不言而喻了,在文本输出中算是一个难点…… 我将借用P先生的思路讲述两种不同风格滚动条,下面切入主题:(实例程序都是显示一张位图 当然, ...
- python使用正則表達式
python中使用正則表達式 1. 匹配字符 正則表達式中的元字符有 . ^ $ * + ? { } [ ] \ | ( ) 匹配字符用的模式有 \d 匹配随意数字 \D 匹配随意非 ...
- NYOJ-104最大和
我看了好多博客,都是拿一维的做基础,一维的比较简单,所以要把二维的化成一维的,一维的题目大意:给了一个序列,求那个子序列的和最大,这时候就可以用dp来做,首先dp[i]表示第i个数能构成的最大子序列和 ...
- #ifndef #define #endif 的用法
1.文件中的#ifndef 头件的中的#ifndef,这是一个很关键的东西.比如你有两个C文件,这两个C文件都include了同一个头文件.而编译时,这两个C文件要一同编译成一个可运行文件,于是问题来 ...
- java克隆总结
对象clone,注意基本类型和指针类型.
- Eclipse 运行ant build.xml
在命令行cmd运行mvn clean install,ant compiler,提示上述信息,是因为 maven的这个插件要求jdk1.6,但是本地电脑环境变量jdk版本为1.7.将JAVA_HOME ...
- Web Api学习一
接触WebApi读的第一篇文章: ASP.NET Web API(一):使用初探,GET和POST数据 实践过程中,用的Fiddler模拟Post请求时收到的对象总是为空null 解决:将文章中的内容 ...
- phpmyadmin登陆提示#2002 无法登录 MySQL 服务器和设置自增
看看mysql启动没有,结果是mysql服务没有启动,找了半天,是这个原因,那就右键计算机->管理->服务->启动mysql服务 设置自增:在显示出来的一行字段定义中把浏览器的滚动条 ...