亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

c# Redis隊列問題

標簽:
C#

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

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消