posts - 52,comments - 30,views - 13万

.NetCore 操作Redis 实现增、删、改、查(模糊查询)、分布式锁 。

需要安装RedisHelper 包

复制代码
using Microsoft.Extensions.Configuration;
using StackExchange.Redis;
using System;
using System.Threading;

namespace Redis
{
    public class RedisHelper
    {
        #region Fileds
        private static string _redisConnection; //= "120.79.77.91:6379,defaultDatabase=0,password=mixdo2018";
        private static int _db = 0;
        private static ConnectionMultiplexer connection;
        #endregion

        #region Constructors
        public RedisHelper(IConfiguration configuration)
        {
            _redisConnection = configuration["RedisConfigHost.Connection"]?.ToString() ?? "";
        }

        public static ConnectionMultiplexer CacheConnection
        {
            get
            {
                try
                {
                    if (connection == null || !connection.IsConnected)
                    {
                        connection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(_redisConnection)).Value;
                    }
                }
                catch (Exception ex)
                {
                    return null;
                }
                return connection;
            }
        }
        #endregion


        #region Methons

        /// <summary>
        /// 缓存当前数据库
        /// </summary>
        public static IDatabase CacheRedis => CacheConnection.GetDatabase(_db);

        /// <summary>
        /// 新增单条值
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public static bool StringSet(string key, string values)
        {
            if (string.IsNullOrEmpty(key) && string.IsNullOrEmpty(values))
                throw new AggregateException("values or is null");
            return CacheRedis.StringSet(key, values);
        }

        /// <summary>
        /// 查询单个key值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static RedisValue GetStringKey(string key)
        {
            return CacheRedis.StringGet(key);
        }

        /// <summary>
        /// 判断key是否存储
        /// </summary>
        /// <param name="key">redis key</param>
        /// <returns></returns>
        public bool KeyExists(string key)
        {
            return CacheRedis.KeyExists(key);
        }

        /// <summary>
        /// 删除单个key
        /// </summary>
        /// <param name="key">redis key</param>
        /// <returns>是否删除成功</returns>
        public bool KeyDelete(string key)
        {
            return CacheRedis.KeyDelete(key);
        }


        /// <summary>
        /// redis 枷锁
        /// </summary>
        /// <param name="key"></param>
        /// <param name="expireTimeSeconds">到期时间秒</param>
        /// <exception cref="Exception"></exception>
        #region 分布式锁
        public static bool LockByRedis(string key, string values)
        {
            try
            {
                //expireTimeSeconds = expireTimeSeconds > 20 ? 10 : expireTimeSeconds;
                //var data = TimeSpan.FromSeconds(expireTimeSeconds);
                //var token = Environment.MachineName;              
                //bool lockflag = CacheRedis.LockTake(key, Thread.CurrentThread.ManagedThreadId, TimeSpan.FromSeconds(expireTimeSeconds));

                bool lockflag = CacheRedis.LockTake(key, values, TimeSpan.FromSeconds(60));//TimeSpan.MaxValue
                if (!lockflag)
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Redis加锁异常:原因{ex.Message}");
                throw new Exception($"Redis加锁异常:原因{ex.Message}");
            }
        }

        /// <summary>
        /// 解锁
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static bool UnLockByRedis(string key, string valuse)
        {
            try
            {
                //Thread.CurrentThread.ManagedThreadId
                //Environment.MachineName
                return CacheRedis.LockRelease(key, valuse);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Redis解锁异常:原因{ex.Message}");
                throw new Exception($"Redis解锁异常:原因{ex.Message}");
            }
        }

        #endregion
        #endregion


        #region Utilities
        #endregion
    }
}
复制代码

 

使用redis进行模糊查询 方式如下

 

posted on   白码一号  阅读(688)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示