標籤:tar rabbit for 分發 tor .text spi 1.3 參考
摘要
這兩天一直在考慮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隊列。既然實現了一生產者,多個消費者,那麼接下來,想實現一種多隊列,然後設定隊列的容量,通過容量,生產者在入隊的時候,根據隊列是否滿,然後對資料進行分發的情況。
轉載:部落格地址:http://www.cnblogs.com/wolf-sun/
c#之Redis隊列