예제 #1
0
        public System.Threading.Tasks.Task PublishAsync <TEvent>(string topic, TEvent domainEvent) where TEvent : class, IEvent
        {
            return(Task.Factory.StartNew(() =>
            {
                var topicBytes = MessageClient.TextToBytes(topic);

                var content = MessageClient.ObjectToJsonString(domainEvent);
                var contentBytes = MessageClient.TextToBytes(content);

                var lenBytes = BitConverter.GetBytes(topicBytes.Length);

                var body = new byte[topicBytes.Length + contentBytes.Length + 4];
                Array.Copy(lenBytes, 0, body, 0, 4);
                Array.Copy(topicBytes, 0, body, 4, topicBytes.Length);
                Array.Copy(contentBytes, 0, body, 4 + topicBytes.Length, contentBytes.Length);
                try
                {
                    MessageClient.Current.SendBytes(new byte[] { 0x01, 0x00, 0x00, 0x02 }, body);
                    Task.Factory.StartNew(() =>
                    {
                        TryFailedItems();
                    });
                }
                catch (Exception) //只关心发送,数据转换失败必须由调用方处理
                {
                    if (body != null && body.Length > 0)
                    {
                        SaveFailedItem(topic, body);
                    }
                }
            }));
        }