c#之Redis隊列


摘要

這兩天一直在考慮redis隊列:一個生產者,多個消費者的情況,這里弄了一個demo進行測試。

一個例子

關於如何引用Redisclient 可以參考之前的這篇文章:c#之Redis實踐list,hashtable

生產者一個線程,然后開啟多個線程用來消費數據。

代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NServiceKit.Redis;
using NServiceKit.ServiceClient;
using System.Threading;
namespace RedisDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread thread = new Thread(run);
            thread.Start();

            Thread[] threads = new Thread[10];
            for (int i = 0; i < threads.Length; i++)
            {
                threads[i] = new Thread(Pull);
                threads[i].Start();
            }

            Console.Read();
        }
        private static void Pull()
        {
            IRedisClientFactory factory = RedisClientFactory.Instance;
            using (IRedisClient client = factory.CreateRedisClient("192.168.1.37", 6379))
            {
                client.Password = "wolfy";
                while (true)
                {
                    if (client.GetListCount("Myqueue") > 0)
                    {
                        string result = client.DequeueItemFromList("Myqueue");
                        //如果獲取的內容為空,將當前線程掛起1s
                        if (string.IsNullOrEmpty(result))
                        {
                            Thread.SpinWait(1000);
                        }
                        else
                        {
                            Console.WriteLine("Threadid:" + Thread.CurrentThread.ManagedThreadId.ToString() + "\t" + result);
                        }
                    }
                    else
                    {
                        //如果當前隊列為空,掛起1s
                        Thread.SpinWait(1000);
                    }
                }
            }

        }
        private static void run()
        {
            IRedisClientFactory factory = RedisClientFactory.Instance;
            using (IRedisClient client = factory.CreateRedisClient("192.168.1.37", 6379))
            {
                client.Password = "wolfy";
                while (true)
                {
                    client.EnqueueItemOnList("Myqueue", DateTime.Now.ToString());
                }
            }


        }
    }
}

測試

總結

關於隊列有考慮過rabbitmq,msmq等,考慮到公司有現成的redis服務器,所以就考慮使用redis隊列。既然實現了一生產者,多個消費者,那么接下來,想實現一種多隊列,然后設置隊列的容量,通過容量,生產者在入隊的時候,根據隊列是否滿,然后對數據進行分發的情況。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM