欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

.Net Core Redis的使用

程序员文章站 2023-12-28 14:46:58
...

1、项目从Nuget中添加引用 Microsoft.Extensions.Caching.Redis

2、创建RedisCacheHelper.cs 帮助类,代码如下

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Caching.Distributed;

namespace Rextec.SOA.Infrastructure
{
    public class RedisCacheHelper
    {
        private static RedisCache _redisCache = null;
        private static RedisCacheOptions options = null;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="instanceName"></param>
        public RedisCacheHelper(string connectionString, string instanceName)
        {
            options = new RedisCacheOptions();
            options.Configuration = connectionString;
            options.InstanceName = instanceName;
            _redisCache = new RedisCache(options);
        }
        /// <summary>
        /// 初始化Redis
        /// </summary>
        public static void InitRedis(string connectionString,string instanceName)
        {
            options = new RedisCacheOptions();
            options.Configuration = connectionString;
            options.InstanceName = instanceName;
            _redisCache = new RedisCache(options);
        }
        /// <summary>
        /// 添加string数据
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="ExprireTime">过期时间 单位小时</param>
        /// <returns></returns>
        public static bool SetStringValue(string key,string value, int ExprireTime = 24)
        {
            if (string.IsNullOrEmpty(key))
            {
                return false;
            }
            try
            {
                _redisCache.SetString(key, value, new DistributedCacheEntryOptions()
                {
                    AbsoluteExpiration = DateTime.Now.AddHours(ExprireTime)
                });
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 获取string数据
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static string GetStringValue(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return null;
            }
            try
            {
                return _redisCache.GetString(key);
            }
            catch(Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 获取数据(对象)
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static T Get<T>(string key)
        {
            string value = GetStringValue(key);
            if (string.IsNullOrEmpty(value))
            {
                return default(T);
            }
            try
            {
                var obj = Json.ToObject<T>(value);
                return obj;
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }
        /// <summary>
        /// 移除数据
        /// </summary>
        /// <param name="key">键</param>
        public static bool Remove(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return false;
            }
            try
            {
                _redisCache.Remove(key);
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 刷新数据
        /// </summary>
        /// <param name="key">键</param>
        public static bool Refresh(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return false;
            }
            try
            {
                _redisCache.Refresh(key);
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 重置数据
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="expireTime">过期时间 单位小时</param>
        public static bool Replace(string key, string value, int expireTime = 24)
        {
            if (Remove(key))
            {
                return SetStringValue(key, value, expireTime);
            }
            else
            {
                return false;
            }
        }
    }
}

3、appsettings.json中配置redis数据连接

 "RedisConnectionStrings": { //redis连接
    "Connection": "127.0.0.1:6379,abortConnect=false",
    "InstanceName": "RextecSOARedis"
  }

4、startup中redis连接设置

//获取redis数据连接
            var redisConnectionString= ((ConfigurationSection)Configuration.GetSection("RedisConnectionStrings:Connection")).Value;
            var redisInstanceName = ((ConfigurationSection)Configuration.GetSection("RedisConnectionStrings:InstanceName")).Value;
            services.AddSingleton(new RedisCacheHelper(redisConnectionString,redisInstanceName));

5、调用示例

RedisCacheHelper.SetStringValue("testvalue", "redis");//添加数据
RedisCacheHelper.GetStringValue("testvalue");//获取数据

 

上一篇:

下一篇: