这两天一直在考虑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队列。既然实现了一生产者,多个消费者,那么接下来,想实现一种多队列,然后设置队列的容量,通过容量,生产者在入队的时候,根据队列是否满,然后对数据进行分发的情况。