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[];
for (int i = ; 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", ))
{
client.Password = "wolfy";
while (true)
{
if (client.GetListCount("Myqueue") > )
{
string result = client.DequeueItemFromList("Myqueue");
//如果获取的内容为空,将当前线程挂起1s
if (string.IsNullOrEmpty(result))
{
Thread.SpinWait();
}
else
{
Console.WriteLine("Threadid:" + Thread.CurrentThread.ManagedThreadId.ToString() + "\t" + result);
}
}
else
{
//如果当前队列为空,挂起1s
Thread.SpinWait();
}
}
} }
private static void run()
{
IRedisClientFactory factory = RedisClientFactory.Instance;
using (IRedisClient client = factory.CreateRedisClient("192.168.1.37", ))
{
client.Password = "wolfy";
while (true)
{
client.EnqueueItemOnList("Myqueue", DateTime.Now.ToString());
}
} }
}
}

测试

c#之Redis队列

总结

关于队列有考虑过rabbitmq,msmq等,考虑到公司有现成的redis服务器,所以就考虑使用redis队列。既然实现了一生产者,多个消费者,那么接下来,想实现一种多队列,然后设置队列的容量,通过容量,生产者在入队的时候,根据队列是否满,然后对数据进行分发的情况。

上一篇:[lua][openresty]代码覆盖率检测的解决方式


下一篇:export a java project to runable jar