Redis 笔记1

Redis缓存基础

redis引用如下:

Nuget  CSRedisCore

需要redis代替系统cache,需要引用:

Nuget  Microsoft.Extensions.Caching.Redis

1、首先建的全局静态类

    public class RedisConfig
    {
        public static CSRedisClient Database0 { get; set; }
    }
View Code

  

2、在startup.cs配置

  使用Redis代替系统缓存

            //使用Redis代替系统缓存
            services.AddDistributedRedisCache(option => {
                option.Configuration = string.Format("{0}:{1},allowAdmin=true,password={2},defaultdatabase={3}", "IP地址", "端号", "密码", 15);//最后一个表
                option.InstanceName = "RedisCache:GatewayOcelotAPI:Name";
            }); 
View Code

   使用第三方Redis工具

            //使用第三方Redis工具
            string config0 = string.Format("{0}:{1},allowAdmin=true,password={2},defaultdatabase={3}", "IP地址", "端口号", "密码", 0);
            //实例化一个单例
            RedisConfig.Database0 = new CSRedis.CSRedisClient(config0);
View Code

3、使用

        private IDistributedCache _cache;

        public ValuesController(IDistributedCache cache)
        {
            _cache = cache;
        }

        //使用第三方redis工具直接访问Redis服务
        [HttpGet("Redis")]
        public string GetValueByRedis()
        {
            //初始化
            RedisHelper.Initialization(RedisConfig.Database0);

            string RedisName = "MyName";

            //最简单的使用
            if (RedisHelper.Exists(RedisName))
            {
                return RedisHelper.Get(RedisName);
            }
            else
            {
                var RedisValues = "this is Value by Redis";
                if (!string.IsNullOrEmpty(RedisValues))
                {
                    RedisHelper.Set(RedisName, RedisValues, 3600);
                }

                return RedisValues;
            }
        }

        //使用系统自带cache
        [HttpGet("Cache")]
        public string GetValueByCache()
        {
            var CacheName = "MyCacheName";
            var CacheValue = "This is Value by Cache";

            //配置选项
            DistributedCacheEntryOptions options = new DistributedCacheEntryOptions();
            options.SetAbsoluteExpiration(TimeSpan.FromSeconds(60));//设置绝对过期时间

            var result = _cache.GetString(CacheName);
            if (result == null)
            {
                result = CacheValue;
                _cache.Set(CacheName, Encoding.UTF8.GetBytes(CacheValue), options);
            }
            return result;
        }
View Code

基本操作完成!

原文地址:https://www.cnblogs.com/myfqm/p/13030292.html