1.首先我们需要安装消息队列服务,它是独立的消息记录的服务,并保存在硬盘文件中。
我们添加名为:DMImgUpload的私有消息队列。
2.定义消息队列的连接字符串建议采用IP:
(1)FormatName:DIRECT=OS:Pac_gzf-PC\Private$\DMImgUpload
(2)FormatName:DIRECT=TCP:192.168.1.105\Private$\DMImgUpload
string queuePath="FormatName:DIRECT=TCP:192.168.1.105\Private$\DMImgUpload";
2.创建实例:【using System.Messaging;】
protected MessageQueueTransactionType transactionType = MessageQueueTransactionType.Automatic;//定义事务
MessageQueue queue = new MessageQueue(queuePath); //根据传入quueuPath创建队列
TimeSpan timeout = TimeSpan.FromSeconds(3);//设置读取消息间隔时间;
queue.DefaultPropertiesToSend.AttachSenderId = false;
queue.DefaultPropertiesToSend.UseAuthentication = false;
queue.DefaultPropertiesToSend.UseEncryption = false;
queue.DefaultPropertiesToSend.AcknowledgeType = AcknowledgeTypes.None;
queue.DefaultPropertiesToSend.UseJournalQueue = false;
3.
/// 接收消息方法
public virtual object Receive()
{
try
{
using (Message message = queue.Receive(timeout, transactionType))
return message;
}
catch (MessageQueueException mqex)
{
if (mqex.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
throw new TimeoutException();
throw mqex;
}
}
/// 发送消息【lable:消息标识,msq:消息】
public virtual void Send(string label, object msg)
{
queue.Send(msg, label, transactionType);
}
5.备注:
当我们跨主机调用时会出现,消息队列权限提示,要在msmq中设置network service权限
消息队列存储可以使字符串,也可以使对象形式。
比如:我们定义一个对象:SolImgCreateModel。接受消息进行强制转换即可:
(SolImgCreateModel)((Message) Receive()).Body;
转载于:https://www.cnblogs.com/guozefeng/p/4170178.html