1.服务端宿主:
using(ServiceHost host = newServiceHost(typeof(MessagingService)))
{
/*异常1:绑定验证失败,因为绑定的ExactlyOnce 属性被设置为 true 而目标队列是非事务性的。
* 无法打开服务主机。通过将 ExactlyOnce 属性设置为 false 或者为此绑定创建
* 事务性队列可以解决此冲突
*/
/*异常2:ServiceMetadataBehavior的 HttpsGetEnabled 属性设置为 Ture,
* 而 HttpsGetUrl 属性是相对地址,但没有 https 基址。请提供 https 基址或
* 将 HttpsGetUrl 设置为绝对地址
*/
stringqueueName = ".\\private$\\Queue_YOYO";
if(!MessageQueue.Exists(queueName))
MessageQueue.Create(queueName);//默认创建非事务性队列
host.Open();
Console.WriteLine("通过消息队列的服务启动");
Console.ReadKey();
}
2.服务端实现代码:
namespaceMessaging
{
[ServiceContract(Namespace="http://yoyozhu.com")]
public interfaceIMessagingService
{
//消息队列是异步通信机制,需设置为oneway
[OperationContract(IsOneWay=true)]
void SendMessage(string msg);
}
/// <summary>
///ServiceBehavior:指定服务类的创建方式,Percall表示每次调用服务方法进行一次服务类的创建
/// </summary>
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
public classMessagingService : IMessagingService
{
#regionIMessagingService 成员
public voidSendMessage(string msg)
{
Console.WriteLine("私有队列消息:{0}",msg);
}
#endregion
}
}
3.服务端配置和异常处理方式
<configuration>
<system.serviceModel>
<services>
<!--服务带上命名空间-->
<service name="Messaging.MessagingService" behaviorConfiguration="serviceBehavior_YOYO">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/MessagingService_YOYO"/>
</baseAddresses>
</host>
<endpoint address="net.msmq://localhost/private/Queue_YOYO" binding="netMsmqBinding"
contract="Messaging.IMessagingService" bindingConfiguration="netMsmq_YOYO" ></endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehavior_YOYO">
<!--异常2使用httpget而不是使用httpsget-->
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<netMsmqBinding>
<!--绑定验证失败:因此在绑定上面找异常1的解决方案-->
<binding name="netMsmq_YOYO" exactlyOnce="false">
<security mode="None"></security>
</binding>
</netMsmqBinding>
</bindings>
</system.serviceModel>
</configuration>
4.客户端产生引用:
MessagingServiceClientclient = new MessagingServiceClient();
client.SendMessage("yoyozhu");
5.停掉服务端,观察消息队列。该队列存在于Win7上如图: