这两天一直在考虑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[] threads = new Thread[10];
for (int i = 0; i < threads.Length; i++)
threads[i] = new Thread(Pull);
private static void Pull()
IRedisClientFactory factory = RedisClientFactory.Instance;
using (IRedisClient client = factory.CreateRedisClient("192.16⑧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.16⑧1.37", 6379))
client.Password = "wolfy";
while (true)
client.EnqueueItemOnList("Myqueue", DateTime.Now.ToString());
}
}
测试
关于队列有考虑过rabbitmq,msmq等,考虑到公司有现成的redis服务器,所以就考虑使用redis队列.既然实现了一生产者,多个消费者,那么此时此刻呢,想实现一种多队列,然后设置队列的容量,通过容量,生产者在入队的时候,根据队列是否满,然后对数据进行分发的情况.
转载:博客地址:http://www.cnblogs.com/wolf-sun/
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[] threads = new Thread[10];
for (int i = 0; i < threads.Length; i++)
threads[i] = new Thread(Pull);
private static void Pull()
IRedisClientFactory factory = RedisClientFactory.Instance;
using (IRedisClient client = factory.CreateRedisClient("192.16⑧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.16⑧1.37", 6379))
client.Password = "wolfy";
while (true)
client.EnqueueItemOnList("Myqueue", DateTime.Now.ToString());
}
}
以上就是土嘎嘎小编为大家整理的c#之Redis队列相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!