コード例 #1
0
        static void Main(string[] args)
        {
            ONSFactoryProperty factoryInfo = new ONSFactoryProperty();

            factoryInfo.setFactoryProperty(factoryInfo.getProducerIdName(), "PID_1234");
            Console.WriteLine("ProducerId:{0}, \nConsumerId:{1},\nPublishTopics:{2},\nMsgContent:{3},\nAccessKey::{4},\nSecretKey::{5} ",
                              factoryInfo.getProducerId(), factoryInfo.getConsumerId(), factoryInfo.getPublishTopics(),
                              factoryInfo.getMessageContent(), factoryInfo.getAccessKey(), factoryInfo.getSecretKey());

            ONSFactory onsfactory = new ONSFactory();

            OrderProducer pProducer = onsfactory.getInstance().createOrderProducer(factoryInfo);

            pProducer.start();

            string key = "abc";

            for (int i = 0; i < 20; ++i)
            {
                Message msg = new Message("Ram_Topic_2", "TagA", "msg from for loop => " + i);
                try
                {
                    SendResultONS sendResult = pProducer.send(msg, key);
                    Console.WriteLine("=> send success : {0} ", sendResult.getMessageId());
                }
                catch (ONSClientException e)
                {
                    Console.WriteLine("\nexception of sendmsg:{0}", e.what());
                }
            }

            Thread.Sleep(1000 * 100);
            pProducer.shutdown();
        }
コード例 #2
0
        /// <summary>
        /// 上游生产者的实现rocketmq的核心方法,其中会由rocketmq自动间接调用AbstractProducerService实例的InternalProduce方法
        /// </summary>
        /// <param name="model">接收的参数</param>
        /// <returns>事务执行结果</returns>
        public bool Process(T model)
        {
            if (_AliyunOnsIsAllowedToSend != "1")
            {
                return(false);
            }
            string requestTraceId = "";
            string key            = this.CreateMessageKey();
            string failureReason  = "";
            string body           = "";
            bool   accomplishment = false;
            int    producedTimes  = 0;
            int    errorTimes     = 0;

            try
            {
                //获取requestTraceId
                requestTraceId = this.GetRequestTraceId();
                //此方法中,只要是普通消息或顺序消息都是空实现,直接返回true
                InternalProcess(model);
                //序列化实体,即消息正文
                body = model.GetType().Name.ToLower() == "system.string" ? model.ToString() : JsonConvert.SerializeObject(model);
                //防止中文乱码
                body = Base64Util.Encode(body);
                //获取生产者
                IONSProducer producer = GetProducer();
                //生成消息实体
                Message message = new Message(this.Topic, this.Tag, body);
                message.setKey(key);
                message.putUserProperties("type", this.MessageType.ToString());
                message.putUserProperties("requestTraceId", requestTraceId);
                //message.putUserProperties("shardingKey", shardingKey);
                //定义消息结果对象
                SendResultONS sendResultONS = null;
                //尝试发送
                sendResultONS = TryToSend(producer, message, null, key, errorTimes);
                //判断结果,一般走不到这步,因为如果发送有问题会直接抛出异常的
                if (sendResultONS == null)
                {
                    throw new Exception("发送BASE消息失败。key=" + key);
                }
                //更新发送状态
                accomplishment = true;
                //更新消费次数
                producedTimes = 1;
            }
            catch (Exception e)
            {
                //将内部捕捉的错误赋值给failureReason,然后由ProduceData的FailureReason属性统一处理
                failureReason = "发送BASE消息,key=" + key + ",捕捉异常:" + e.ToString();
                return(false);
            }
            finally
            {
                //无论是否有异常都统一写入生产日志
                LogData(key, body, "", "", failureReason, accomplishment, producedTimes, failureReason != "" ? false : true);
            }
            return(true);
        }
コード例 #3
0
ファイル: ProducerMessage.cs プロジェクト: omcdev/blockchain
        public void SendNormalMessage(T byteBody, string tags)
        {
            Message msg = new Message(factoryInfo.getPublishTopics(), tags, Newtonsoft.Json.JsonConvert.SerializeObject(byteBody));

            msg.setKey(Guid.NewGuid().ToString());
            SendResultONS sendResult = producer.send(msg);

            LogHelper.Info($"send success {sendResult.getMessageId()}");
        }
コード例 #4
0
ファイル: TransactionProducer.cs プロジェクト: Aqmic/Dcp.Lib
        public virtual SendResultONS send(Message msg, LocalTransactionExecuter executer)
        {
            SendResultONS ret = new SendResultONS(ONSClient4CPPPINVOKE.TransactionProducer_send(swigCPtr, Message.getCPtr(msg), LocalTransactionExecuter.getCPtr(executer)), true);

            if (ONSClient4CPPPINVOKE.SWIGPendingException.Pending)
            {
                throw ONSClient4CPPPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
コード例 #5
0
        public virtual SendResultONS send(Message msg, string shardingKey)
        {
            SendResultONS ret = new SendResultONS(ONSClient4CPPPINVOKE.OrderProducer_send(swigCPtr, Message.getCPtr(msg), shardingKey), true);

            if (ONSClient4CPPPINVOKE.SWIGPendingException.Pending)
            {
                throw ONSClient4CPPPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
コード例 #6
0
        /// <summary>
        /// 代理OrderProducer实例的send方法
        /// </summary>
        /// <param name="message">Message实例</param>
        /// <param name="parameter">parameter参数</param>
        /// <returns>SendResultONS实例</returns>
        public SendResultONS send(Message message, object parameter)
        {
            SendResultONS sendResultONS = null;

            if (_producer != null)
            {
                sendResultONS = _producer.send(message);
            }
            return(sendResultONS);
        }
コード例 #7
0
        public virtual SendResultONS send(Message msg, MessageQueueONS mq)
        {
            SendResultONS ret = new SendResultONS(ONSClient4CPPPINVOKE.Producer_send__SWIG_1(swigCPtr, Message.getCPtr(msg), MessageQueueONS.getCPtr(mq)), true);

            if (ONSClient4CPPPINVOKE.SWIGPendingException.Pending)
            {
                throw ONSClient4CPPPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
コード例 #8
0
        /// <summary>
        /// 代理TransactionProducer实例的send方法
        /// </summary>
        /// <param name="message">Message实例</param>
        /// <param name="parameter">parameter参数</param>
        /// <returns>SendResultONS实例</returns>
        public SendResultONS send(Message message, object parameter)
        {
            SendResultONS sendResultONS = null;

            if (_producer != null)
            {
                ONSLocalTransactionExecuter executer = parameter as ONSLocalTransactionExecuter;
                sendResultONS = _producer.send(message, executer);
            }
            return(sendResultONS);
        }
コード例 #9
0
        /// <summary>
        /// 代理OrderProducer实例的send方法
        /// </summary>
        /// <param name="message">Message实例</param>
        /// <param name="parameter">parameter参数</param>
        /// <returns>SendResultONS实例</returns>
        public SendResultONS send(Message message, object parameter)
        {
            SendResultONS sendResultONS = null;

            if (_producer != null)
            {
                string shardingKey = parameter.ToString();
                DebugUtil.Debug("shardingKey:" + shardingKey);
                sendResultONS = _producer.send(message, shardingKey);
            }
            return(sendResultONS);
        }
コード例 #10
0
        /// <summary>
        /// 尝试发送消息
        /// </summary>
        /// <param name="producer">生产者实例</param>
        /// <param name="message">消息实例</param>
        /// <param name="parameter">发送所需参数</param>
        /// <param name="key">消息的唯一标识</param>
        /// <param name="errorTimes">本系统自己自己执行时发现出错后,记录的错误次数(此参数不适用于生产次数)</param>
        /// <returns></returns>
        protected SendResultONS TryToSend(IONSProducer producer, Message message, object parameter, string key, int errorTimes)
        {
            SendResultONS sendResultONS = null;

            try
            {
                sendResultONS = producer.send(message, parameter);
            }
            catch (Exception e)
            {
                //错误计数累加
                errorTimes++;
                //无论是阿里云服务不可用,还是生产者挂了,一共3次机会,即执行1次,然后最多重试两次
                if (errorTimes < 3)
                {
                    //如果生产者挂了
                    if (e.ToString().IndexOf("Your producer has been shutdown.") >= 0)
                    {
                        //置空producer
                        producer = null;
                        //重新获取producer并启动
                        producer = GetProducer();
                        //等待3秒
                        System.Threading.Thread.Sleep(3000);
                    }
                    else
                    {
                        //如果是阿里云服务不可用,等待1秒
                        System.Threading.Thread.Sleep(1000);
                    }

                    //递归
                    sendResultONS = TryToSend(producer, message, parameter, key, errorTimes);
                }
                else
                {
                    //重试2次都还是失败
                    string className    = this.GetType().Name;
                    string methodName   = "Process";
                    string errorMessage = _Environment + "." + _ApplicationAlias + "." + className + "." + methodName + "尝试发送时,出现了第" + errorTimes + "次出错,key=" + key + ":" + e.ToString();
                    //记录本地错误日志
                    DebugUtil.Debug(errorMessage);
                    //记录FATAL日志
                    ONSHelper.SaveLog(LogTypeEnum.FATAL, className, methodName, errorMessage);
                    //发送邮件
                    ONSHelper.SendDebugMail(_Environment + "." + _ApplicationAlias + "." + className + "." + methodName + "尝试发送时出错", errorMessage);
                    //抛出异常
                    throw new Exception(errorMessage);
                }
            }

            return(sendResultONS);
        }
コード例 #11
0
 public void SendOrderMessage(string tag, string byteBody, string shardingKey)
 {
     try
     {
         Message       msg        = new Message(factoryInfo.getPublishTopics(), tag, byteBody);
         SendResultONS sendResult = orderProducer.send(msg, shardingKey);
         Console.WriteLine("send success {0}", sendResult.getMessageId());
     }
     catch (Exception ex)
     {
         Console.WriteLine("send failure{0}", ex.ToString());
     }
 }
コード例 #12
0
ファイル: ProducerMessage.cs プロジェクト: omcdev/blockchain
 /// <summary>
 /// 发送普通消息
 /// </summary>
 /// <param name="byteBody"></param>
 /// <param name="tags"></param>
 public void SendNormalMessage(string byteBody, string tags)
 {
     try
     {
         Message msg = new Message(factoryInfo.getPublishTopics(), tags, byteBody);
         msg.setKey(Guid.NewGuid().ToString());
         SendResultONS sendResult = producer.send(msg);
         Console.WriteLine("send success {0}", sendResult.getMessageId());
     }
     catch (Exception ex)
     {
         LogHelper.Error($"send failure {ex.ToString()}");
     }
 }
コード例 #13
0
 /// <summary>
 /// 发送定时消息
 /// </summary>
 /// <param name="tag">二级标签</param>
 /// <param name="byteBody">消息内容</param>
 /// <param name="keys">设置代表消息的业务关键属性,请尽可能全局唯一</param>
 /// <param name="deliverTime">单位 ms,指定一个时刻,在这个时刻之后才能被消费</param>
 public void SendTimedMessage(string tag, string byteBody, string keys, long deliverTime)
 {
     try
     {
         Message msg = new Message(factoryInfo.getPublishTopics(), tag, byteBody);
         msg.setKey(keys);
         msg.setStartDeliverTime(deliverTime);
         SendResultONS sendResult = timedProducer.send(msg);
     }
     catch (Exception ex)
     {
         //发送失败处理
     }
 }
コード例 #14
0
        public static void SendMessage(byte[] msgBody)
        {
            Message msg = new Message(Ons_Topic, "", "");

            msg.setBody(msgBody, msgBody.Length);
            try
            {
                SendResultONS sendResult = _producer.send(msg);
                Console.WriteLine("send success {0}", sendResult.getMessageId());
            }
            catch (Exception ex)
            {
                Console.WriteLine("send failure{0}", ex.ToString());
            }
        }
コード例 #15
0
        public static void SendMessage(string msgBody, String tag = "RegisterLog")
        {
            // Message msg = new Message(Ons_Topic, tag, msgBody);
            Message msg = new Message(Ons_Topic, tag, msgBody);

            msg.setKey(Guid.NewGuid().ToString());
            try
            {
                SendResultONS sendResult = _producer.send(msg);
                Console.WriteLine("send success {0}", sendResult.getMessageId());
            }
            catch (Exception ex)
            {
                Console.WriteLine("send failure{0}", ex.ToString());
            }
        }
コード例 #16
0
        /// <summary>
        /// 发送一个消息
        /// <para>作    者:蔡亚康</para>
        /// <para>创建时间:2019-03-14</para>
        /// </summary>
        /// <param name="msgBody">消息数据</param>
        /// <param name="tag"></param>
        public void SendMessage(string msgBody, String tag = "")
        {
            msgBody = Base64Helper.Base64Encode(msgBody);
            Message msg = new Message(_topicId, tag, msgBody);

            msg.setKey(Guid.NewGuid().ToString());
            try
            {
                SendResultONS sendResult = _producer.send(msg);
            }
            catch (Exception ex)
            {
                //Console.WriteLine("send failure{0}", ex.ToString());
                LogWriter.Write("BaseProducer_SendMessage", ex.ToString(), LoggerType.Error);
            }
        }
コード例 #17
0
 public void SendOrderMessage(string tag, List <T> byteBody, string shardingKey)
 {
     try
     {
         foreach (var item in byteBody)
         {
             Message       msg        = new Message(factoryInfo.getPublishTopics(), tag, Newtonsoft.Json.JsonConvert.SerializeObject(item));
             SendResultONS sendResult = orderProducer.send(msg, shardingKey);
             Console.WriteLine("send success {0}", sendResult.getMessageId());
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("send failure{0}", ex.ToString());
     }
 }
コード例 #18
0
        public static void SendOrderMessage(string msgBody, String tag = "RegisterLog", String key = "test")
        {
            Message msg = new Message(Ons_Topic, tag, msgBody);

            byte[] data = new byte[10];
            msg.setBody(data, 10);
            msg.setKey(Guid.NewGuid().ToString());
            try
            {
                SendResultONS sendResult = _orderproducer.send(msg, key);
                Console.WriteLine("send success {0}", sendResult.getMessageId());
            }
            catch (Exception ex)
            {
                Console.WriteLine("send failure{0}", ex.ToString());
            }
        }
コード例 #19
0
ファイル: ProducerMessage.cs プロジェクト: omcdev/blockchain
 /// <summary>
 /// 发送普通消息
 /// </summary>
 public void SendNormalMessage(List <T> byteBody, string tags)
 {
     try
     {
         foreach (var item in byteBody)
         {
             Message msg = new Message(factoryInfo.getPublishTopics(), tags, Newtonsoft.Json.JsonConvert.SerializeObject(item));
             msg.setKey(Guid.NewGuid().ToString());
             SendResultONS sendResult = producer.send(msg);
             LogHelper.Info($"send success {sendResult.getMessageId()}");
         }
     }
     catch (Exception ex)
     {
         LogHelper.Error($"send failure {ex.ToString()}");
     }
 }
コード例 #20
0
 public void SendTimedMessage(string tag, List <T> byteBody, string keys, long deliverTime)
 {
     try
     {
         foreach (var item in byteBody)
         {
             Message msg = new Message(factoryInfo.getPublishTopics(), tag, Newtonsoft.Json.JsonConvert.SerializeObject(item));
             msg.setKey(keys);
             msg.setStartDeliverTime(deliverTime);
             SendResultONS sendResult = timedProducer.send(msg);
         }
     }
     catch (Exception ex)
     {
         //发送失败处理
     }
 }
コード例 #21
0
 public void SendTransactionMessage(string tag, string byteBody, string shardingKey)
 {
     try
     {
         Message msg = new Message(factoryInfo.getPublishTopics(), tag, byteBody);
         msg.setKey(shardingKey);
         LocalTransactionExecuter myExecuter = new MyLocalTransactionExecuter();
         //事务检查
         myChecker.check(msg);
         SendResultONS sendResult = transactionProducer.send(msg, myExecuter);
         //事务执行
         myExecuter.execute(msg);
     }
     catch (Exception ex)
     {
         Console.WriteLine("\nexception of sendmsg:{0}");
     }
 }
コード例 #22
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            // 配置账号, 从控制台获取设置
            ONSFactoryProperty factoryInfo = new ONSFactoryProperty();

            // AccessKeyId 阿里云身份验证,在阿里云服务器管理控制台创建
            factoryInfo.setFactoryProperty(ONSFactoryProperty.AccessKey, "Your access key");
            // AccessKeySecret 阿里云身份验证,在阿里云服务器管理控制台创建
            factoryInfo.setFactoryProperty(ONSFactoryProperty.SecretKey, "Your access secret");
            // 您在控制台创建的 Group ID
            factoryInfo.setFactoryProperty(ONSFactoryProperty.ProducerId, "GID_example");
            // 您在控制台创建的 Topic
            factoryInfo.setFactoryProperty(ONSFactoryProperty.PublishTopics, "T_example_topic_name");
            // 设置 TCP 接入域名,进入控制台的实例管理页面的“获取接入点信息”区域查看
            factoryInfo.setFactoryProperty(ONSFactoryProperty.NAMESRV_ADDR, "NameSrv_Addr");
            // 设置日志路径
            factoryInfo.setFactoryProperty(ONSFactoryProperty.LogPath, "C://log");
            // 创建生产者实例
            // 说明:生产者实例是线程安全的,可用于发送不同 Topic 的消息。基本上,您每一个线程
            // 只需要一个生产者实例
            Producer producer = ONSFactory.getInstance().createProducer(factoryInfo);

            // 启动客户端实例
            producer.start();
            // 创建消息对象
            Message msg = new Message(factoryInfo.getPublishTopics(), "tagA", "Examplemessage body");

            msg.setKey(Guid.NewGuid().ToString());
            for (int i = 0; i < 32; i++)
            {
                try
                {
                    SendResultONS sendResult = producer.send(msg);
                    Console.WriteLine("send success {0}", sendResult.getMessageId());
                }
                catch (Exception ex)
                {
                    Console.WriteLine("send failure{0}", ex.ToString());
                }
            }
            // 在您的线程即将退出时,关闭生产者实例
            producer.shutdown();
        }
コード例 #23
0
ファイル: Form1.cs プロジェクト: minhua1983/RocketTester
        private void sendButton_Click(object sender, EventArgs e)
        {
            Form1.ActiveForm.FormClosing += ActiveForm_FormClosing;

            /*
             * Message msg = new Message(
             * //Message Topic
             *  factoryInfo.getPublishTopics(),
             *  //Message Tag
             *  "TagA",
             *  //Message Body
             *  factoryInfo.getMessageContent()
             * );
             * //*/

            Message msg = new Message(
                //Message Topic
                factoryInfo.getPublishTopics(),
                //Message Tag
                "TagA",
                //Message Body
                messageTextBox.Text.Trim()
                );

            // 设置代表消息的业务关键属性,请尽可能全局唯一
            // 以方便您在无法正常收到消息情况下,可通过 MQ 控制台查询消息并补发。
            // 注意:不设置也不会影响消息正常收发
            //msg.setKey("ORDERID_100");

            // 发送消息,只要不抛出异常,就代表发送成功
            try
            {
                LocalTransactionExecuter myExecuter = new MyLocalTransactionExecuter();
                SendResultONS            sendResult = producer.send(msg, myExecuter);
            }
            catch (Exception exception)
            {
                Console.WriteLine("\nexception of sendmsg:{0}", exception.ToString());
            }
        }
コード例 #24
0
 private global::System.IntPtr SwigDirectorsend__SWIG_1(global::System.IntPtr msg, global::System.IntPtr mq)
 {
     return(SendResultONS.getCPtr(send(new Message(msg, false), new MessageQueueONS(mq, false))).Handle);
 }
コード例 #25
0
        /// <summary>
        /// 上游生产者的实现rocketmq的核心方法,其中会由rocketmq自动间接调用AbstractTransactionProducerService实例的InternalProduce方法
        /// </summary>
        /// <param name="model">接收的参数</param>
        /// <returns>事务执行结果</returns>
        public bool Process(T model)
        {
            if (_AliyunOnsIsAllowedToSend != "1")
            {
                return(false);
            }
            string requestTraceId = "";
            string key            = this.CreateMessageKey();
            string failureReason  = "";
            string body           = "";
            bool   accomplishment = false;
            int    producedTimes  = 0;
            int    errorTimes     = 0;

            try
            {
                //获取requestTraceId
                requestTraceId = this.GetRequestTraceId();
                //序列化实体,即消息正文
                body = model.GetType().Name.ToLower() == "system.string" ? model.ToString() : JsonConvert.SerializeObject(model);
                //防止中文乱码
                body = Base64Util.Encode(body);
                //获取生产者
                IONSProducer producer = GetProducer();
                //Message实体的body不能为空
                Message message = new Message(this.Topic, this.Tag, body);
                message.setKey(key);
                message.putUserProperties("type", this.MessageType.ToString());
                message.putUserProperties("requestTraceId", requestTraceId);

                //获取InternalProcess方法
                MethodInfo methodInfo = this.GetType().GetMethod("InternalProcess", BindingFlags.NonPublic | BindingFlags.Instance);

                string executerMethodName = methodInfo.ReflectedType.FullName + "." + methodInfo.Name;
                string checkerMethodName  = methodInfo.ReflectedType.FullName + "." + methodInfo.Name;

                //将方式实例和方式实例的参数都存到消息的属性中去。
                //message.putUserProperties("executerMethodParameter", data);
                message.putUserProperties("executerMethod", executerMethodName);
                //message.putUserProperties("checkerMethodParameter", data);
                message.putUserProperties("checkerMethod", checkerMethodName);

                //方式实例字典中不存在的话,则试图新增到字典中去
                if (!ONSHelper.ExecuterMethodDictionary.ContainsKey(executerMethodName))
                {
                    ONSHelper.ExecuterMethodDictionary.TryAdd(executerMethodName, methodInfo);
                }
                if (!ONSHelper.CheckerMethodDictionary.ContainsKey(checkerMethodName))
                {
                    ONSHelper.CheckerMethodDictionary.TryAdd(checkerMethodName, methodInfo);
                }

                //实例化LocalTransactionExecuter对象
                ONSLocalTransactionExecuter executer = new ONSLocalTransactionExecuter();
                //定义消息结果对象
                SendResultONS sendResultONS = null;
                //尝试发送
                sendResultONS = TryToSend(producer, message, executer, key, errorTimes);
                //判断结果,一般走不到这步,因为如果发送有问题会直接抛出异常的
                if (sendResultONS == null)
                {
                    throw new Exception("发送TRAN消息失败。key=" + key);
                }
                //更新发送状态
                accomplishment = true;
                //更新消费次数
                producedTimes = 1;
            }
            catch (Exception e)
            {
                failureReason = "发送TRAN消息,key=" + key + ",在TranProducerService中(非Executer或Checker中),捕获异常" + e.ToString();
                LogData(key, body, "", "", failureReason, accomplishment, producedTimes, false);
                return(false);
            }

            return(true);
        }
コード例 #26
0
 private global::System.IntPtr SwigDirectorsend(global::System.IntPtr msg, string shardingKey)
 {
     return(SendResultONS.getCPtr(send(new Message(msg, false), shardingKey)).Handle);
 }
コード例 #27
0
ファイル: SendResultONS.cs プロジェクト: Aqmic/Dcp.Lib
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SendResultONS obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }