net core WebApi-- cache artifact Redis

table of Contents

@

Foreword

Mid-Autumn Festival had finished unknowingly have not moved this project for almost two weeks, and recently began to engage in business needs finally back cloud services, and decisively direct net core huh, in the middle of doing a lot of problems encountered, this follow-up will be a little bit listed include solutions, today first before digging a hole to fill.

Redis

Thing I read in the cache before mentioned, Cookie , the Session , Cache several different ways cache, Cookie is the presence of the client browser, Session is essentially a client's storage, as is the Cache server, but if it is distributed then this may be several ways in addition to Cookie other two have a little problem, after all, a service stores only a single, multi-service interaction itself if more than one, then the need to involve, for example, a service done Cache memory, other services need to send an internal signal or http request, performs a corresponding operation according to other service requests.

Of course, this is not used Redis under the premise, Redis is the artifact to solve the distributed cache, the equivalent of a server dedicated itself to read and write data processing, can be understood as a data server (personal feeling ...), As for his own business It distributed only to business need to execute, need to use the data cache can be called directly read and write operations of Redis (of course, Redis configure each service to be consistent).

Redis installation and configuration on Linux configuration deployment _ novice to (d) - Redis installation and configuration has been said, it is to use Redis and then do a little groundwork.

use

First of all, as long as the library must be introduced Nuget package, we April.Util introduced Microsoft.Extensions.Caching.Redis , of course, there are other StackExchange.Redis , CSRedisCore , the official first try it here, the official expansion pack address .

After completion of the introduction, we have to address configuration directory appsettings.json.
Configuration
Then we look at Redis method, after all, look at all the third-party call and then wrapped it according to their needs.
Redis

Is the first to initial configuration information, and then create an entity object, calling the method described here, the default value is the value of byte [], of course, there are the official extension methods.
Redis
Well, after the way we start Util it.

RedisUtil

First of all, we still have to do first configuration information, configuration information has already been written in appsettings, here directly AprilConfig added on in.

private static string _IsOpenCache = string.Empty;
        /// <summary>
        /// 是否使用Redis
        /// </summary>
        public static bool IsOpenCache
        {
            get
            {
                if (string.IsNullOrEmpty(_IsOpenCache))
                {
                    _IsOpenCache = Configuration["Redis:IsOpenRedis"];
                }
                if (_IsOpenCache.ToLower() == "true")
                {
                    return true;
                }
                return false;
            }
        }

        private static string _RedisConnectionString = string.Empty;
        /// <summary>
        /// Redis默认连接串
        /// </summary>
        public static string RedisConnectionString
        {
            get
            {
                if (string.IsNullOrEmpty(_RedisConnectionString))
                {
                    _RedisConnectionString = Configuration["Redis:ConnectionString"];
                }
                return _RedisConnectionString;
            }
        }

After setting the configuration information is complete, start the initialization method of Redis.

        private static RedisCache _redisCache = null;
        private static RedisCacheOptions options = null;
        /// <summary>
        /// 初始化Redis
        /// </summary>
        public static void InitRedis()
        {
            if (AprilConfig.IsOpenCache)
            {
                _redisCache = new RedisCache(GetOptions());
            }
        }
        /// <summary>
        /// 获取配置项信息
        /// </summary>
        /// <returns></returns>
        protected static RedisCacheOptions GetOptions()
        {
            options = new RedisCacheOptions();
            options.Configuration = AprilConfig.RedisConnectionString;
            options.InstanceName = "April.Redis";
            return options;
        }
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="ExprireTime">过期时间</param>
        public static void Add(string key, object value, int ExprireTime = 10)
        {
            if (string.IsNullOrEmpty(key))
            {
                return;
            }
            string strValue = string.Empty;
            try
            {
                strValue = JsonConvert.SerializeObject(value);
            }
            catch (Exception ex)
            {
                LogUtil.Error($"Redis.Add转换失败:{ex.Message}");
            }
            if (!string.IsNullOrEmpty(strValue))
            {
                _redisCache.SetString(key, strValue, new Microsoft.Extensions.Caching.Distributed.DistributedCacheEntryOptions()
                {
                    AbsoluteExpiration = DateTime.Now.AddMinutes(ExprireTime)
                });
            }
        }
        /// <summary>
        /// 获取数据(对象)
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static T Get<T>(string key)
        {
            string value = Get(key);
            if (string.IsNullOrEmpty(value))
            {
                return default(T);
            }
            T obj = default(T);
            try
            {
                obj = JsonConvert.DeserializeObject<T>(value);
            }
            catch (Exception ex)
            {
                LogUtil.Error($"Redis.Get转换失败:{ex.Message},数据:{value}");
            }
            return obj;
        }
        /// <summary>
        /// 移除数据
        /// </summary>
        /// <param name="key">键</param>
        public static void Remove(string key)
        {
            if (!string.IsNullOrEmpty(key))
            {
                _redisCache.Remove(key);
            }
        }
        /// <summary>
        /// 重置数据
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="expireTime">过期时间</param>
        public static void Replace(string key, object value, int expireTime = 10)
        {
            if (!string.IsNullOrEmpty(key))
            {
                Remove(key);
                Add(key, value, expireTime);
            }
        }

The specific methods used, not much here to write the code address see net core Webapi List , I feel more attached to the code, and he is accustomed to copy and paste, look at a packaged method, you must go to his source code (if but even if), the use of such methods as well as their business needs package will be a good help with the words, after all, will use is the first step, the second step would be to change the package is the third step, that is, to write their own the final stage (the phrase is purely encourage each other).

test

Well, after the finish, used to test it again, do not want their sort of thing can not be used eventually, monotony is not terrible, terrible is not know the final results.
New
test
result

Obtain
test
result

Covering
ps: said to be covered, in fact, delete and add -, - |||
test
result

delete
test
result

summary

I write to you basically over, simply illustrates the use of Redis, or follow-up will continue to update, such as so many database, if the random switching, will not have any other problems, and so after redis storage, apply their knowledge, with Fang admitted the mistake, the wrong and can change, change on the line .

Guess you like

Origin www.cnblogs.com/AprilBlank/p/11571365.html