• .NET Core使用缓存


    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,

  • 相关阅读:
    使用RPC的接口创建账户同时购买内存并为其抵押CPU和NET资源
    使用RPC的接口创建账户
    【移动安全基础篇】——21、Android脱壳思路
    插件
    NGUI 优化
    影子
    优化文章索引
    MVC
    《你不常用的c#之XX》
    CMake
  • 原文地址:https://www.cnblogs.com/xsj1989/p/13856537.html
Copyright © 2020-2023  润新知