1.MemoryCache 服务器端缓存
添加服务:services.AddMemoryCache();
使用:注入IMemoryCache _memoryCache;
var cityList = new List<City>(); if (!_memoryCache.TryGetValue("cities", out test)) { cityList = _cityServices.GetAll(); var cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(5)) .SetAbsoluteExpiration(TimeSpan.FromDays(1)); //缓存清除之后调用回调 //cacheEntryOptions.RegisterPostEvictionCallback(); _memoryCache.Set("cities",cityList); } return cityList;
2.CacheTagHelper自己查
3.使用Redis;NuGet安装Microsoft.Extensions.Caching.Redis
StartUp.cs注册服务:
services.AddDistributedRedisCache(options=> { options.Configuration = "localhost"; options.InstanceName = "redis-for-albums"; });
4.使用,注入IDistributedCache distributedCache,代码
var cityList = new List<City>(); var cityListBytes = _distributedCache.Get("cities"); if (cityListBytes == null) { cityList = _cityServices.GetAll(); var cityString = JsonConvert.SerializeObject(cityList); byte[] cityEncode = Encoding.UTF8.GetBytes(cityString); var cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(5)); _distributedCache.Set("cities", cityEncode); } else { byte[] cityEncode = _distributedCache.Get("cities"); var cityString = Encoding.UTF8.GetString(cityEncode); cityList = JsonConvert.DeserializeObject<List<City>>(cityString); } return cityList;
5.ResponseCache,