c# - 在 Azure 队列存储中传递对象消息

标签 c# azure azure-storage-queues

我正在尝试找到一种将对象传递到 Azure 队列的方法。我找不到方法来做到这一点。

正如我所见,我可以传递字符串或字节数组,这对于传递对象来说不太舒服。

是否可以将自定义对象传递到队列?

谢谢!

最佳答案

您可以使用以下类作为示例:

 [Serializable]
    public abstract class BaseMessage
    {
        public byte[] ToBinary()
        {
            BinaryFormatter bf = new BinaryFormatter();
            byte[] output = null;
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Position = 0;
                bf.Serialize(ms, this);
                output = ms.GetBuffer();
            }
            return output;
        }

        public static T FromMessage<T>(CloudQueueMessage m)
        {
            byte[] buffer = m.AsBytes;
            T returnValue = default(T);
            using (MemoryStream ms = new MemoryStream(buffer))
            {
                ms.Position = 0;
                BinaryFormatter bf = new BinaryFormatter();
                returnValue = (T)bf.Deserialize(ms);
            }
            return returnValue;
        }
    }

然后是 StdQueue(强类型队列):

   public class StdQueue<T> where T : BaseMessage, new()
    {
        protected CloudQueue queue;

        public StdQueue(CloudQueue queue)
        {
            this.queue = queue;
        }

        public void AddMessage(T message)
        {
            CloudQueueMessage msg =
            new CloudQueueMessage(message.ToBinary());
            queue.AddMessage(msg);
        }

        public void DeleteMessage(CloudQueueMessage msg)
        {
            queue.DeleteMessage(msg);
        }

        public CloudQueueMessage GetMessage()
        {
            return queue.GetMessage(TimeSpan.FromSeconds(120));
        }
    }

然后,您所要做的就是继承BaseMessage:

[Serializable]
public class ParseTaskMessage : BaseMessage
{
    public Guid TaskId { get; set; }

    public string BlobReferenceString { get; set; }

    public DateTime TimeRequested { get; set; }
}

并创建一个适用于该消息的队列:

CloudStorageAccount acc;
            if (!CloudStorageAccount.TryParse(connectionString, out acc))
            {
                throw new ArgumentOutOfRangeException("connectionString", "Invalid connection string was introduced!");
            }
            CloudQueueClient clnt = acc.CreateCloudQueueClient();
            CloudQueue queue = clnt.GetQueueReference(processQueue);
            queue.CreateIfNotExist();
            this._queue = new StdQueue<ParseTaskMessage>(queue);

希望这有帮助!

关于c# - 在 Azure 队列存储中传递对象消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8550702/

相关文章:

c# - 原子检查文件是否存在并打开它

node.js - 从 azure blob Nodejs 下载文件

azure - Azure 中的 ace::/64 地址空间是什么意思?

json - Azure 存储 REST API 能否以 JSON 格式发送响应?

c# - WPF Grid.IsSharedSizeScope 跨多个网格

c# - 在编辑器模板 (MVC 5) 中访问远程验证属性

c# - C# 中的实体和 N 层架构

c# - 为什么我的 Azure 网站不再可见?

c# - 我可以使用 Azure 存储队列中的 Response<SendReceipt> 验证消息是否已成功发送