Bootstrap

Web开发:使用stackexchange.redis库对redis进行增删改查

一、安装第三方库

二、官网

StackExchange.Redis |通用型 redis 客户端

三、连接示例

 private static string redisConnectionString = "localhost:6379,password=yourpassword,defaultDatabase=0,syncTimeout=10000";

 private static string redisConnectionString = "localhost:6379,defaultDatabase=0,syncTimeout=10000";

四、封装:增删改查

namespace ConsoleApp2
{
    public class RedisData
    {
        public string Key { get; set; }
        public string KeyTail { get; set; }
        public string Value { get; set; }

        public int? TTLDays { get; set; }
        public int? TTLMins { get; set; }
        public int? TTLSecs { get; set; }

        public DateTime? ExpirationTime { get; set; } 

        public DateTime QueryTime { get; set; }
    }

    public static class RedisExtension
    {
        // 默认的 Redis 连接字符串
        private static string redisConnectionString = "localhost:6379,defaultDatabase=0,syncTimeout=10000";

        // 使用 Lazy 实例化连接,只会在第一次使用时连接 Redis
        private static Lazy<ConnectionMultiplexer> redis = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(redisConnectionString));

        // 通过连接获取 Redis 数据库
        private static IDatabase db => redis.Value.GetDatabase();

        /// <summary>
        /// 尝试连接
        /// </summary>
        /// <param name="conn"></param>
        /// <returns></returns>
        public static async Task<bool> TryConnectAsync(string conn = null)
        {
            // 如果传入了新的连接字符串,更新 Redis 连接
            if (!string.IsNullOrWhiteSpace(conn))
            {
                redisConnectionString = conn;
                // 清理现有连接,强制重新连接
                redis = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(redisConnectionString));
            }

            try
            {
                // 通过插入 测试 Redis 连接
                string testKey = Guid.NewGuid().ToString();
                await InsertAsync(testKey, testKey);
                await DeleteAsync(testKey);
                return true; // 连接成功
            }
            catch (Exception ex)
            {
                return false; // 连接失败
            }
        }

        /// <summary>
        /// 【增加】设置一个键值对
        /// </summary>
        /// <param name="key">第一个入参示例“NewYork:School:John”(文件夹形式);第三个入参可以传递形如TimeSpan.FromSeconds(30),传null则表明永不过期</param>
        /// <param name="value"></param>
        /// <param name="expiration"></param>
        public static async Task<bool> InsertAsync(string key, string value, TimeSpan? expiration = null)
        {
            if (await GetRedisDataByKeyAsync(key) != null)
            {
                return false;
            }

            if (await db.KeyExistsAsync(key))
            {
                return false;
            }
            if (expiration == null) // 不设置超时时间
            {
                await db.StringSetAsync(key, value);
            }
            else // 设置超时时间
            {
                await db.StringSetAsync(key, value, expiration);
            }
            return true;
        }

        /// <summary>
        /// 【更新】设置一个键值对
        /// </summary>
        /// <param name="key">第一个入参示例“NewYork:School:John”(文件夹形式);第三个入参可以传递形如TimeSpan.FromSeconds(30),传null则表明永不过期</param>
        /// <param name="value"></param>
        /// <param name="expiration"></param>
        public static async Task<bool> UpdateAsync(string key, string value, TimeSpan? expiration = null)
        {
            if (await GetRedisDataByKeyAsync(key) == null)
            {
                return false;
            }
            if (expiration == null) // 不设置超时时间
            {
                await db.StringSetAsync(key, value);
            }
            else // 设置超时时间
            {
                await db.StringSetAsync(key, value, expiration);
            }
            return true;
        }

        /// <summary>
        /// 【查询】键值对信息
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static async Task<RedisData> GetRedisDataByKeyAsync(string key)
        {
            if (await db.KeyExistsAsync(key)) // 键存在
            {
                RedisData data = new RedisData()
                {
                    Key = key,
                    Value = await db.StringGetAsync(key),
                    KeyTail = key.Split(':').LastOrDefault(),
                    QueryTime = DateTime.Now
                };
                var ttl = await db.KeyTimeToLiveAsync(key);
                if (ttl != null)
                {
                    data.ExpirationTime = DateTime.Now.Add(ttl.Value);
                    data.TTLDays = Convert.ToInt32(ttl.Value.TotalDays);
                    data.TTLMins = Convert.ToInt32(ttl.Value.TotalMinutes);
                    data.TTLSecs = Convert.ToInt32(ttl.Value.TotalSeconds);
                }
                return data;
            }
            return null;
        }

        /// <summary>
        /// 【删除】指定键,只有在键存在时才删除
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static async Task<bool> DeleteAsync(string key)
        {
            if (await db.KeyExistsAsync(key)) // 判断键是否存在
            {
                return await db.KeyDeleteAsync(key); // 如果存在,删除键
            }
            return false; // 如果键不存在,返回 false
        }

        /// <summary>
        /// 【自定义指令】
        /// </summary>
        /// 示例输入:PING
        /// <returns></returns>
        public static async Task<string> SendCommandAsync(string command)
        {
            string result = "";
            try
            {
                result = (await db.ExecuteAsync(command)).ToString();
                return result; // 返回响应
            }
            catch (Exception ex)
            {

                return ex.Message.ToString(); 
            }
            
        }
    }
}

;