1.先在控制面板添加MSMQ组件
image.png
2.此时可以在计算机管理里面看到消息队列的服务
image.png
3.敲代码
一个消息类:
[Serializable]
public class MsgModel
{
public string id { get; set; }
public string Name { get; set; }
public MsgModel() { }
public MsgModel(string _id, string _Name)
{
id = _id;
Name = _Name;
}
public override string ToString()
{
if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(Name)) return "";
return string.Format("id--{0},Name--{1}", id, Name);
}
}
基本代码:
/// <summary>
/// 创建消息队列
/// </summary>
/// <param name="name">消息队列名称</param>
/// <returns></returns>
public void CreateNewQueue(string name)
{
if (!System.Messaging.MessageQueue.Exists(".\\private$\\" + name))//检查是否已经存在同名的消息队列
{
System.Messaging.MessageQueue mq = System.Messaging.MessageQueue.Create(".\\private$\\" + name);
mq.Label = "private$\\" + name;
Response.Write("创建成功!<br/>");
}
else
{
//System.Messaging.MessageQueue.Delete(".\\private$\\" + name);//删除一个消息队列
Response.Write("已经存在<br/>");
}
}
private void sendComplexMsg<T>(T t)
{
//实例化MessageQueue,并指向现有的一个名称为VideoQueue队列
MessageQueue MQ = new MessageQueue(@".\private$\MsgQueue");
//MQ.Send("消息测试", "测试消息");
System.Messaging.Message message = new System.Messaging.Message();
message.Label = "复杂消息lable";
message.Body = t;
MQ.Send(message);
Response.Write("成功发送消息," + DateTime.Now + "<br/>");
}
private T receiveComplexMsg<T>()
{
MessageQueue MQ = new MessageQueue(@".\private$\MsgQueue");
//调用MessageQueue的Receive方法接收消息
if (MQ.GetAllMessages().Length > 0)
{
System.Messaging.Message message = MQ.Receive(TimeSpan.FromSeconds(5));
if (message != null)
{
message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(T) });//消息类型转换
T msg = (T)message.Body;
return msg;
}
}
return default(T);
}
执行代码:
protected void Page_Load(object sender, EventArgs e)
{
CreateNewQueue("MsgQueue");//创建一个消息队列
sendComplexMsg<MsgModel>(new MsgModel("100", "completed"));
MsgModel m = receiveComplexMsg<MsgModel>();
Response.Write(m.ToString());
}
执行CreateNewQueue后,可以看到:
image.png
执行sendComplexMsg后,可以看到:
image.png
执行receiveComplexMsg后,消息就消失了:
image.png
网友评论