abp使用Redis笔记

1.xxx.WebCore项目nuget安装Abp.RedisCache,注意是WebCore项目
2.appsettings.json添加配置:

  "RedisCache": {
    "ConnectionString": "192.168.3.201:30150",
    "DatabaseId": 0
  }

3.xxx.WebCoreModule添加AbpRedisCacheModule

    [DependsOn(
         typeof(MesApplicationModule),
         typeof(MesEntityFrameworkModule),
         typeof(AbpAspNetCoreModule)
        , typeof(AbpAspNetCoreSignalRModule)
        , typeof(AbpRedisCacheModule)
     )]
    public class SaasWebCoreModule : AbpModule

4.PreInitialize方法添加

            //使用redis缓存(必须放在使用redis缓存之前)
            Configuration.Caching.UseRedis(options =>
            {
                options.ConnectionString = _appConfiguration["RedisCache:ConnectionString"];
                options.DatabaseId = _appConfiguration.GetValue<int>("RedisCache:DatabaseId");
            });

            //设置所有缓存的默认过期时间(必须放在使用redis缓存之前)
            Configuration.Caching.ConfigureAll(cache =>
            {
                cache.DefaultAbsoluteExpireTime = TimeSpan.FromMinutes(20);
            });
            //设置某个缓存的默认过期时间 根据 "CacheName" 来区分(必须放在使用redis缓存之前)
            Configuration.Caching.Configure("caches", cache =>
            {
                cache.DefaultAbsoluteExpireTime = TimeSpan.FromSeconds(10);
            });

5.Application层通过注入的方式使用

private readonly ICacheManager _cacheManager;
       #region 测试缓存

        [HttpGet]
        [AbpAllowAnonymous]
        public async Task TestRedis()
        {
            //试着从Redis缓存中获取数据,如果没获取到,则到数据库中获取
            //var username = _cacheManager.GetCache("caches").Get("username", () => "subendong");
            //var password = _cacheManager.GetCache("caches").Get("password", () => "123456");
            await _cacheManager.GetCache("caches").SetAsync("username", "subendong", TimeSpan.FromSeconds(10));
            var value = await _cacheManager.GetCache("caches").GetOrDefaultAsync("username");
        }

        #endregion

 

posted @ 2022-03-22 19:26  屌丝大叔的笔记  阅读(711)  评论(0编辑  收藏  举报