[selfless sharing: ASP.NET Core project combat (Chapter 11) Asp.net Core cache MemoryCache and Redis

Original text: [selfless sharing: ASP.NET Core project combat (Chapter 11) Asp.net Core cache MemoryCache and Redis ...
Original text: [selfless sharing: ASP.NET Core project combat (Chapter 11) Asp.net Core cache MemoryCache and Redis

Catalog Index

[selfless sharing: ASP.NET Core project actual combat] directory index

brief introduction

After N years of repeated attempts, I have read numerous materials on the Internet, downloaded more than a dozen source code references on GitHub, and finally wrote a simple package for Memory and Redis. In order to be unified and easy to use, we have implemented a unified interface for both caches, i.e. ICacheService. Microsoft also has a lot of them through IDistributedCache, which you can refer to https://docs.asp.net/en/latest/performance/caching/distributed.html There are also many good packages on GitHub. Here we will not introduce them one by one. Let's refer to them for your reference. Now we are engaged in Asp.net There are not a lot of core materials, and there are few Chinese materials, and they are basically copied in the same way. For those who only know ABCDEFG for me, the process is very difficult. An article often needs to be read four or five times, translated line by line, sentence by sentence. It's tears when we say more. Let's start. During this period, I got a lot of help from my friends. Thank you!

Cache interface ICacheService

Whether it's cache or database, we're CRUD operation. There's nothing to explain about the interface. I'm very clear about the comments. Here's what I'll list:

Verify that the cache entry exists

1 /// <summary> 2 /// Verify that the cache entry exists 3 /// </summary> 4 /// <param name="key">cache Key</param> 5 /// <returns></returns> 6 bool Exists(string key); 7 8 /// <summary> 9 /// Verify cache entry exists (asynchronously) 10 /// </summary> 11 /// <param name="key">cache Key</param> 12 /// <returns></returns> 13 Task<bool> ExistsAsync(string key);

Add cache

1 /// <summary> 2 /// Add cache 3 /// </summary> 4 /// <param name="key">cache Key</param> 5 /// <param name="value">cache Value</param> 6 /// <returns></returns> 7 bool Add(string key, object value); 8 9 /// <summary> 10 /// Add cache (asynchronous mode) 11 /// </summary> 12 /// <param name="key">cache Key</param> 13 /// <param name="value">cache Value</param> 14 /// <returns></returns> 15 Task<bool> AddAsync(string key, object value); 16 17 /// <summary> 18 /// Add cache 19 /// </summary> 20 /// <param name="key">cache Key</param> 21 /// <param name="value">cache Value</param> 22 /// <param name="expiresSliding">Sliding expiration time (if there is an operation within the expiration time, extend the expiration time at the current time point)</param> 23 /// <param name="expiressAbsoulte">Absolute expiration time</param> 24 /// <returns></returns> 25 bool Add(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte); 26 27 /// <summary> 28 /// Add cache (asynchronous mode) 29 /// </summary> 30 /// <param name="key">cache Key</param> 31 /// <param name="value">cache Value</param> 32 /// <param name="expiresSliding">Sliding expiration time (if there is an operation within the expiration time, extend the expiration time at the current time point)</param> 33 /// <param name="expiressAbsoulte">Absolute expiration time</param> 34 /// <returns></returns> 35 Task<bool> AddAsync(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte); 36 37 /// <summary> 38 /// Add cache 39 /// </summary> 40 /// <param name="key">cache Key</param> 41 /// <param name="value">cache Value</param> 42 /// <param name="expiresIn">Cache duration</param> 43 /// <param name="isSliding">Whether to slide expiration (if there is an operation within the expiration time, extend the expiration time with the current time point)</param> 44 /// <returns></returns> 45 bool Add(string key, object value, TimeSpan expiresIn, bool isSliding = false); 46 47 /// <summary> 48 /// Add cache (asynchronous mode) 49 /// </summary> 50 /// <param name="key">cache Key</param> 51 /// <param name="value">cache Value</param> 52 /// <param name="expiresIn">Cache duration</param> 53 /// <param name="isSliding">Whether to slide expiration (if there is an operation within the expiration time, extend the expiration time with the current time point)</param> 54 /// <returns></returns> 55 Task<bool> AddAsync(string key, object value, TimeSpan expiresIn, bool isSliding = false);

Delete cache

1 /// <summary> 2 /// Delete cache 3 /// </summary> 4 /// <param name="key">cache Key</param> 5 /// <returns></returns> 6 bool Remove(string key); 7 8 /// <summary> 9 /// Delete cache (asynchronous mode) 10 /// </summary> 11 /// <param name="key">cache Key</param> 12 /// <returns></returns> 13 Task<bool> RemoveAsync(string key); 14 15 /// <summary> 16 /// Bulk delete cache 17 /// </summary> 18 /// <param name="key">cache Key aggregate</param> 19 /// <returns></returns> 20 void RemoveAll(IEnumerable<string> keys); 21 22 /// <summary> 23 /// Batch delete cache (asynchronous mode) 24 /// </summary> 25 /// <param name="key">cache Key aggregate</param> 26 /// <returns></returns> 27 Task RemoveAllAsync(IEnumerable<string> keys);

Get cache

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

Modify cache

1 /// <summary> 2 /// Modify cache 3 /// </summary> 4 /// <param name="key">cache Key</param> 5 /// <param name="value">New cache Value</param> 6 /// <returns></returns> 7 bool Replace(string key, object value); 8 9 /// <summary> 10 /// Modify cache (asynchronous mode) 11 /// </summary> 12 /// <param name="key">cache Key</param> 13 /// <param name="value">New cache Value</param> 14 /// <returns></returns> 15 Task<bool> ReplaceAsync(string key, object value); 16 17 /// <summary> 18 /// Modify cache 19 /// </summary> 20 /// <param name="key">cache Key</param> 21 /// <param name="value">New cache Value</param> 22 /// <param name="expiresSliding">Sliding expiration time (if there is an operation within the expiration time, extend the expiration time at the current time point)</param> 23 /// <param name="expiressAbsoulte">Absolute expiration time</param> 24 /// <returns></returns> 25 bool Replace(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte); 26 27 /// <summary> 28 /// Modify cache (asynchronous mode) 29 /// </summary> 30 /// <param name="key">cache Key</param> 31 /// <param name="value">New cache Value</param> 32 /// <param name="expiresSliding">Sliding expiration time (if there is an operation within the expiration time, extend the expiration time at the current time point)</param> 33 /// <param name="expiressAbsoulte">Absolute expiration time</param> 34 /// <returns></returns> 35 Task<bool> ReplaceAsync(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte); 36 37 /// <summary> 38 /// Modify cache 39 /// </summary> 40 /// <param name="key">cache Key</param> 41 /// <param name="value">New cache Value</param> 42 /// <param name="expiresIn">Cache duration</param> 43 /// <param name="isSliding">Whether to slide expiration (if there is an operation within the expiration time, extend the expiration time with the current time point)</param> 44 /// <returns></returns> 45 bool Replace(string key, object value, TimeSpan expiresIn, bool isSliding = false); 46 47 /// <summary> 48 /// Modify cache (asynchronous mode) 49 /// </summary> 50 /// <param name="key">cache Key</param> 51 /// <param name="value">New cache Value</param> 52 /// <param name="expiresIn">Cache duration</param> 53 /// <param name="isSliding">Whether to slide expiration (if there is an operation within the expiration time, extend the expiration time with the current time point)</param> 54 /// <returns></returns> 55 Task<bool> ReplaceAsync(string key, object value, TimeSpan expiresIn, bool isSliding = false);

Cache implementation class MemoryCache

MemoryCache is relatively simple, with Microsoft's relatively complete documents and some good articles, which we have used for a long time.

We create a new cache implementation class MemoryCacheService implementation interface, ICacheService

public class MemoryCacheService :ICacheService { }

Inject IMemoryCache through the constructor:

protected IMemoryCache _cache;

public MemoryCacheService(IMemoryCache cache)
{
_cache = cache;
}


There are two ways to implement the interface: asynchronous and synchronous. We save chapters and time. You can't write asynchronous ones, just add them yourself.

Verify that the cache entry exists

In MemoryCache, we use TryGetValue to check whether the Key exists

1 /// <summary> 2 /// Verify that the cache entry exists 3 /// </summary> 4 /// <param name="key">cache 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 }

Add cache

Three ways to add:

1 /// <summary> 2 /// Add cache 3 /// </summary> 4 /// <param name="key">cache Key</param> 5 /// <param name="value">cache 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 /// Add cache 22 /// </summary> 23 /// <param name="key">cache Key</param> 24 /// <param name="value">cache Value</param> 25 /// <param name="expiresSliding">Sliding expiration time (if there is an operation within the expiration time, extend the expiration time at the current time point)</param> 26 /// <param name="expiressAbsoulte">Absolute expiration time</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 /// Add cache 48 /// </summary> 49 /// <param name="key">cache Key</param> 50 /// <param name="value">cache Value</param> 51 /// <param name="expiresIn">Cache duration</param> 52 /// <param name="isSliding">Whether to slide expiration (if there is an operation within the expiration time, extend the expiration time at the current time point)</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 }

Delete cache

Single delete and batch delete

1 /// <summary> 2 /// Delete cache 3 /// </summary> 4 /// <param name="key">cache 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 /// Bulk delete cache 18 /// </summary> 19 /// <param name="key">cache Key aggregate</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 }

Get cache

1 /// <summary> 2 /// Get cache 3 /// </summary> 4 /// <param name="key">cache 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 /// Get cache 16 /// </summary> 17 /// <param name="key">cache 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 /// Get cache collection 29 /// </summary> 30 /// <param name="keys">cache Key aggregate</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 }

Modify cache

1 /// <summary> 2 /// Modify cache 3 /// </summary> 4 /// <param name="key">cache Key</param> 5 /// <param name="value">New cache 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 /// Modify cache 25 /// </summary> 26 /// <param name="key">cache Key</param> 27 /// <param name="value">New cache Value</param> 28 /// <param name="expiresSliding">Sliding expiration time (if there is an operation within the expiration time, extend the expiration time at the current time point)</param> 29 /// <param name="expiressAbsoulte">Absolute expiration time</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 /// Modify cache 48 /// </summary> 49 /// <param name="key">cache Key</param> 50 /// <param name="value">New cache Value</param> 51 /// <param name="expiresIn">Cache duration</param> 52 /// <param name="isSliding">Whether to slide expiration (if there is an operation within the expiration time, extend the expiration time with the current time point)</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 }

Final release:

public void Dispose()
{
if (_cache != null)
_cache.Dispose();
GC.SuppressFinalize(this);
}




Redis, cache implementation class

Redis is usually run by Liunx. We [(Chapter 10)] release the project to run the Core project on Linux It introduces how to develop and run the Core project on Linux. Of course, I believe that many friends still develop and test on windows. Here is a Redis and management software on windows. If you don't have or don't know how to find a friend, you can download it and test Redis on Windows: the connection may fail Baidu online disk Extraction code: uglb Baidu online disk Extraction code: gl0e

After installing the first one, start the Redis service. The interface of the management software is also very simple

Let's take a look at our RedisCacheService:

In order to unify management and switch use, our RedisCacheService also implements the interface ICacheService

public class RedisCacheService : ICacheService { }

Again, we inject through the constructor:

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;
}





Note: we need to add a redis package: Microsoft.Extensions.Caching.Redis, it's official, but I don't know whether it's the cause of my program or what. It's always failed to restore, and it's not good to command to restore the package forcibly, so I used a transplant package: Microsoft.Extensions.Caching.Redis.Core If you can, you'd better use the official bag.

Here we write a method to combine the Key value and the instance name, that is, the Key value is changed to the instance name + Key

public string GetKeyForRedis(string key)
{
return _instance + key;
}


Verify that the cache entry exists

1 /// <summary> 2 /// Verify that the cache entry exists 3 /// </summary> 4 /// <param name="key">cache 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 }

Add cache

Note: I have browsed a lot of data and found that Redis supports sliding and absolute expiration, but they are all inherited unified interfaces, so it's useless to add a method sliding expiration here.

1 /// <summary> 2 /// Add cache 3 /// </summary> 4 /// <param name="key">cache Key</param> 5 /// <param name="value">cache 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 /// Add cache 17 /// </summary> 18 /// <param name="key">cache Key</param> 19 /// <param name="value">cache Value</param> 20 /// <param name="expiresSliding">Sliding expiration time (if there is an operation within the expiration time, extend the expiration time at the current time point,Redis Invalid in)</param> 21 /// <param name="expiressAbsoulte">Absolute expiration time</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 /// Add cache 33 /// </summary> 34 /// <param name="key">cache Key</param> 35 /// <param name="value">cache Value</param> 36 /// <param name="expiresIn">Cache duration</param> 37 /// <param name="isSliding">Whether to slide expiration (if there is an operation within the expiration time, extend the expiration time at the current time point,Redis Invalid in)</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 }

Delete cache

1 /// <summary> 2 /// Delete cache 3 /// </summary> 4 /// <param name="key">cache 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 /// Bulk delete cache 16 /// </summary> 17 /// <param name="key">cache Key aggregate</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(item)); 27 }

Get cache

1 /// <summary> 2 /// Get cache 3 /// </summary> 4 /// <param name="key">cache 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 /// Get cache 24 /// </summary> 25 /// <param name="key">cache 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 /// Get cache collection 42 /// </summary> 43 /// <param name="keys">cache Key aggregate</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 }

Modify cache

1 /// <summary> 2 /// Modify cache 3 /// </summary> 4 /// <param name="key">cache Key</param> 5 /// <param name="value">New cache 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 /// Modify cache 23 /// </summary> 24 /// <param name="key">cache Key</param> 25 /// <param name="value">New cache Value</param> 26 /// <param name="expiresSliding">Sliding expiration time (if there is an operation within the expiration time, extend the expiration time at the current time point)</param> 27 /// <param name="expiressAbsoulte">Absolute expiration time</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 /// Modify cache 44 /// </summary> 45 /// <param name="key">cache Key</param> 46 /// <param name="value">New cache Value</param> 47 /// <param name="expiresIn">Cache duration</param> 48 /// <param name="isSliding">Whether to slide expiration (if there is an operation within the expiration time, extend the expiration time with the current time point)</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 }

Likewise, release:

public void Dispose()
{
if (_connection != null)
_connection.Dispose();
GC.SuppressFinalize(this);
}




Startup.cs And cache configuration

We are [(Chapter 8)] read configuration file (2) read user-defined configuration file We also put the cached configuration in our custom configuration file siteconfig.json Medium:

We write a class to get several configurations:

CacheProvider:  _ isUseRedis - use Redis or not

_ connectionString - Redis connection

_ instanceName -- Redis instance name

At Startup.cs In ConfigureServices(IServiceCollection services) of:

First add: services.AddMemoryCache();

Determine whether to use Redis. If you do not use Redis, MemoryCache will be used by default:

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, it's finished. It's less than a month since the Core was also studied, so there must be some places that are not well written. I hope you can point out that if there is a higher scheme or method, please let me know. Thank you!

Hope to learn with you Asp.net Core 

Just started to contact, the level is limited, many things are their own understanding and browsing the online God of information, if there is something wrong and do not understand, I hope you correct!

although Asp.net Core is very hot now, but many materials on the Internet are the same copy of the previous article, so there are many problems I haven't solved yet, I hope you can help!

Please respect the achievements of labor http://yuangang.cnblogs.com

24 May 2020, 08:16 | Views: 4146

Add new comment

For adding a comment, please log in
or create account

0 comments