MQ和WS技术相结合其实就可以看做是一个简单的ESB程序,这样可以通过调用服务来实现消息中间件的处理功能,可以开发包括消息推送、接收、处理的应用程序。WS是在Windows操作系统中才会有的,是集成到系统中的,一个WS在开启后会一直运行,直到停止该WS。在具体的项目中开发的WS是作为组件存在的,也就是说系统中的某部分需要实时运行,这时候可以考虑开发WS组件。
上面的程序分布图是结合上文的MQ来绘制的详细的架构图,其中的数据发送部分的程序在上文已经有介绍,这里不再详细讨论,下面的代码就是演示了分布图中的Service Handle data和Save data部分的功能,具体功能如下代码:
using System;
using System.IO;
using System.ServiceProcess;
using System.Threading;
using System.Timers;
using System.Messaging;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
//declare a MQ
private MessageQueue queue;
public Service1()
{
InitializeComponent();
//create a path for queue
string strpath = ".\\Private$\\EKTestQueue";
//create a messagequeue and assign a path for this queue
queue= new MessageQueue(strpath);
//the queue formatter that can get queuebody based on the formatter
queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
}
/// <summary>
/// service start event
/// when we start this service then it will run this method
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
//used to debug the code when start this service
Thread.Sleep(30000);
}
/// <summary>
/// service stop event
/// </summary>
protected override void OnStop()
{
}
/// <summary>
/// get message from queue and save the message to file
/// </summary>
private void GetAndWriteMessage()
{
//recevie a new one MQ
var ms=queue.Receive();
//save the data to file
if (ms!=null)
{
this.AddTextLine(ms.Body.ToString());
}
}
/// <summary>
/// save the MQ message to file
/// </summary>
/// <param name="line">the message that want save</param>
private void AddTextLine(string line)
{
try
{
//save the message to Message.txt file
FileStream file=new FileStream("D:\\Message.txt",FileMode.OpenOrCreate,FileAccess.ReadWrite);
StreamWriter writer=new StreamWriter(file);
writer.BaseStream.Seek(0, SeekOrigin.End);
writer.WriteLine(line+"\r\n");
writer.Flush();
writer.Close();
file.Close();
file.Dispose();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private void timer1_Elapsed(object sender, ElapsedEventArgs e)
{
GetAndWriteMessage();
}
}
}
在开发完成服务后不能够直接运行使用,而是要将服务安装到系统的Services中才能够查看服务是否正常运行,因为服务不同于一般的应用程序,想要使用服务就必须将服务安装到系统当中。另外服务的调试也是很麻烦的一件事,因为服务不同于应用程序,想要调试它就不能采用普通的调试方法了,这里介绍一种附加进程的调试方法,还有其它如写日志等的调试方法,可以查看网上的文章来详细了解。
首先要打开控制台并进入到C:/Windows/Microsoft.Net/Framework/v4.0.30319中,运行InstallUtil.exe工具,并添加相应的开发的服务程序,然后回车运行就可以安装,如下所示:
C:/Windows/Microsoft.Net/Framework/v4.0.30319>InstallUtil.exe C:\Code\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe
安装完成后查看Services工具中的服务如下图所示:
在不使用服务后也可以删除服务,删除方法类似于服务的安装,具体方法如下所示:
C:/Windows/Microsoft.Net/Framework/v4.0.30319>InstallUtil.exe/u C:\Code\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe
原文:http://blog.csdn.net/zhang_xinxiu/article/details/44026471