Exemple #1
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            //mq对象
            using var mq = new Producer
                  {
                      //主题
                      Topic = "lmi_datas",
                      //服务地址
                      NameServerAddress = "127.0.0.1:9876",
                  };

            mq.Start();
            int i = 1;

            //轮询发消息
            while (true)
            {
                var content = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss.fff");
                var message = new NewLife.RocketMQ.Protocol.Message()
                {
                    BodyString     = content,
                    Keys           = (i++).ToString(),
                    Tags           = i % 2 == 0 ? "even" : "odd",
                    Flag           = 0,
                    WaitStoreMsgOK = true
                };
                //发送消息(生产消息)
                var    sr  = mq.Publish(message);
                string log = $"发送成功的消息,内容>{content},MsgId={sr.MsgId},BrokerName= {sr.Queue.BrokerName} ,QueueId={sr.Queue.QueueId},QueueOffset= {sr.QueueOffset}";
                Console.WriteLine(log);
                Task.Delay(TimeSpan.FromSeconds(10)).Wait();
            }
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message">消息内容</param>
        /// <param name="key">key</param>
        /// <param name="msgDelayLevel">消息延迟等级,0=不延迟,具体各等级对应的延迟时间参考消息队列服务端的属性配置文件【messageDelayLevel】,默认为 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h</param>
        /// <returns>发送结果</returns>
        public Result Send(Object message, string key = "", int msgDelayLevel = 0)
        {
            Result res = new Result();

            try
            {
                if (!(message is Byte[] buf))
                {
                    if (!(message is String str))
                    {
                        str = message.ToJson();
                    }

                    buf = str.GetBytes();
                }

                NewLife.RocketMQ.Protocol.Message msg = new NewLife.RocketMQ.Protocol.Message()
                {
                    Body = buf, Tags = _configModel.Tags, Keys = key, DelayTimeLevel = msgDelayLevel
                };
                var sendRes = _producer.Publish(msg);
                res.IsSucceed = sendRes.Status == NewLife.RocketMQ.Protocol.SendStatus.SendOK;
            }
            catch (System.Exception e)
            {
                res.Message = e.Message;
            }
            return(res);
        }