隊列工廠之RedisMQ

本次和大家分享的是RedisMQ隊列的用法,前兩篇文章隊列工廠之(MSMQ)隊列工廠之RabbitMQ分別簡單介紹對應隊列環境的搭建和常用方法的使用,加上本篇分享的RedisMQ那麼就完成了咋們隊列工廠"三劍客"的目標了哈哈;Redis的作用不僅僅侷限於隊列,更多的一般都使用它的key,value的形式來存儲session或者hash的方式存儲一些常用的數據,當然這不是本章分享的內容(之前有些文章有講過redis的使用場景和代碼分享各位可以看下),這QueueReposity-隊列工廠最後一篇結束後,筆者後面分享的可能是netcore方面的一些東西了,vs2017出來了簡單創建netcore項目之後發現與之前的版本有些變動,例如:沒有project.json,怎麼配置生成跨平臺程序等問題,需要一個一個學習和嘗試,網上搜索的文章還很少,全靠閱讀全英文的官網來學習了哈哈;希望大家能夠喜歡本篇文章,也希望各位多多"掃碼支持"和"推薦"謝謝!

 

Redis安裝和RedisClient工具的使用

 封裝RedisMQ隊列的讀和寫

 隊列工廠之RedisMQ測試用例

 

下面一步一個腳印的來分享:

 Redis安裝和RedisClient工具的使用

首先要使用redis需要下載安裝Redis,這裏由於之前的文章有講解在windows下怎麼搭建redis服務,所以不再贅述,各位可以點擊搭建Redis服務端,並用客戶端連接,因此我這裏直接分享怎麼使用RedisClient工具,這工具使用起來比較簡單和方便,首先去這個地址下載:

http://dlsw.baidu.com/sw-search-sp/soft/a2/29740/RedisClient20140730.1406883096.exe

安裝-》打開軟件,能看到如圖的界面:

-》點擊“Server”-》Add-》輸入一個暱稱,你redis服務端的ip,端口-》確認即可:

這個時候你redisclient的配置工作就完成了是不是很簡單啊,-》再來點擊剛纔創建暱稱-》雙擊打開redis的第一個數據庫db0(這裏就是在沒有指定數據庫位置時候存儲數據的地方)-》能看到你存儲的數據key:

如果想看某個name的數據直接雙擊對應的name就行了-》這裏是我redis服務存儲的一個hash數據的截圖:

是不是很方便,這個客戶端可以直接刪除你不想要的數據-》右鍵選中您想刪除的name-》Delete即可刪除:

怎麼樣,這個RedisClient工具學會了麼,是不是挺簡單的呢;

 

 封裝RedisMQ隊列的讀和寫

到這裏終於來到我們代碼分享的時刻了,儘管QueueReposity-隊列工廠已經開源了源碼,這裏還是單獨分享一次只有RedisMQ的代碼;首先創建一個名稱爲:QRedisMQ的class-》繼承 PublicClass.ConfClass<T>-》再實現接口IQueue,最後就有了我們實現接口方法體代碼:

/// <summary>
    /// RedisMQ
    /// </summary>
    public class QRedisMQ : PublicClass.ConfClass<QRedisMQ>, IQueue
    {
        private IRedisClient redis = null;

        public void Create()
        {
            if (string.IsNullOrWhiteSpace(this.ApiUrl) ||
                string.IsNullOrWhiteSpace(this.UserPwd)) { throw new Exception("創建QRedisMQ隊列需要指定隊列:ApiUrl,UserPwd"); }

            this.ApiKey = string.IsNullOrWhiteSpace(this.ApiKey) ? "6379" : this.ApiKey;
            redis = redis ?? new RedisClient(this.ApiUrl, Convert.ToInt32(this.ApiKey), this.UserPwd);
        }

        public long Total(string name = "Redis_01")
        {
            if (redis == null) { throw new Exception("請先創建隊列連接"); }
            if (string.IsNullOrWhiteSpace(name)) { throw new Exception("name不能爲空"); }

            return redis.GetListCount(name);
        }

        public Message Read(string name = "Redis_01")
        {
            if (redis == null) { throw new Exception("請先創建隊列連接"); }
            if (string.IsNullOrWhiteSpace(name)) { throw new Exception("name不能爲空"); }

            var message = new Message();
            try
            {
                message.Label = name;
                var result = redis.DequeueItemFromList(name);
                if (string.IsNullOrWhiteSpace(result)) { return message; }
                message.Body = result;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return message;
        }

        public bool Write(string content, string name = "Redis_01")
        {
            if (redis == null) { throw new Exception("請先創建隊列連接"); }
            if (string.IsNullOrWhiteSpace(content) || string.IsNullOrWhiteSpace(name)) { throw new Exception("content和name不能爲空"); }
            redis.EnqueueItemOnList(name, content);
            return true;
        }

        public void Dispose()
        {
            if (redis != null)
            {
                redis.Dispose();
                redis = null;
            }
        }


        //public List<Message> ReadAll()
        //{
        //    throw new NotImplementedException();
        //}
    }

這裏用到的Redis的dll是引用了相關的nuget包:

封裝的隊列Redis工廠流程同樣是:創建(Create)-》讀(Read)|寫(Write)-》釋放(Dispose);有了具體的RedisMQ實現類,然後還需利用工廠模式提供的方法來創建這個類的實例:

/// <summary>
    /// ==================
    /// author:神牛步行3
    /// des:該列工廠開源,包括隊列有MSMQ,RedisMQ,RabbitMQ
    /// blogs:http://www.cnblogs.com/wangrudong003/
    /// ==================
    /// 隊列工廠
    /// </summary>
    public class QueueReposity<T> where T : class,IQueue, new()
    {
        public static IQueue Current
        {
            get
            {
                return PublicClass.ConfClass<T>.Current;
            }
        }
    }

到這兒RedisMQ工廠代碼就完成了,下面開始分享我們的測試用例;

 

 隊列工廠之RedisMQ測試用例

通過上面配置環境和封裝自己的方法,這裏寫了一個簡單的測試用例,分爲Server(加入消息隊列)和Client(獲取消息隊列),首先來看Server端的代碼:

/// <summary>
    /// 隊列服務端測試用例
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Redis_Server();

            // RabbitMQ_Server();

            //MSMQ_Server();
        }

        private static void Redis_Server()
        {
            //實例化QRedisMQ對象
            var mq = QueueReposity<QRedisMQ>.Current;

            try
            {
                Console.WriteLine("Server端創建:RedisMQ實例");
                mq.Create();

                var num = 0;
                do
                {
                    Console.WriteLine("輸入循環數量(數字,0表示結束):");
                    var readStr = Console.ReadLine();
                    num = string.IsNullOrWhiteSpace(readStr) ? 0 : Convert.ToInt32(readStr);

                    Console.WriteLine("插入數據:");
                    for (int i = 0; i < num; i++)
                    {
                        var str = "我的編號是:" + i;
                        mq.Write(str);
                        Console.WriteLine(str);
                    }
                } while (num > 0);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                Console.WriteLine("釋放。");
                mq.Dispose();
            }
            Console.ReadLine();
        }

通過:創建(Create)-》讀(Read)|寫(Write)-》釋放(Dispose) 的流程來使用我們的隊列工廠,此時我們運行下這個Server端,然後分別錄入4次參數:

能看到截圖的文字描述,這些測試數據插入到了redis的隊列中,下面我們通過第一節說的RedisClient工具查看數據,點擊隊列名稱如:

通過工具能看到我們剛纔插入的數據,然後我們來通過測試用例的client端讀取隊列,具體代碼:

/// <summary>
    /// 隊列客戶端測試用例
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            RedisMQ_Client();

          //  RabbitMQ_Client();

            //MSMQ_Client();
        }

        private static void RedisMQ_Client()
        {
            //實例化QRedisMQ對象
            var mq = QueueReposity<QRedisMQ>.Current;
            try
            {
                Console.WriteLine("Client端創建:RedisMQ實例");
                mq.Create();

                while (true)
                {
                    try
                    {
                        var total = mq.Total();
                        if (total > 0) { Console.WriteLine("隊列條數:" + total); }

                        var result = mq.Read();
                        if (result.Body == null) { continue; }
                        Console.WriteLine(string.Format("接受隊列{0}:{1}", result.Label, result.Body));
                    }
                    catch (Exception ex)
                    { Console.WriteLine("異常信息:" + ex.Message); }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Console.WriteLine("釋放。");
                mq.Dispose();
            }
        }

運行生成的exe,看效果:

通過圖形能看出讀取隊列的數據正如我們想的那樣依次讀取,測試用例測試RedisMQ的代碼沒問題;以上對封裝RedisMQ的代碼分享和環境搭建講解,到這裏隊列工廠(MSMQ,RabbitMQ,RedisMQ)就分享完了,希望能給您帶來好的幫助,謝謝閱讀;


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章