Windows Azure AppFabric 入门教学系列 (二):一个简单的Service Bus例子

 

 

声明:由于Windows Azure SDK和相关工具的更新,下文下载链接可能已失效,最新链接更新如下:

 

Windows Azure Tools for Microsoft Visual Studio (已包含SDK)

Windows Azure AppFabric SDK V1.0 - October Update

 

 

 

 

 

 

 

本文是Windows Azure AppFabric入门教学的第二篇文章,可以说是正式的开始学习AppFabric了。为了使后续的学习顺利进行请确保已浏览本教程的第一篇文章,并以按照该文完成了AppFabric项目和命名空间的创建。我们知道,AppFabirc由Service Bus 和 Access Control Service组成。本篇教学以一个简单的Echo程序来向大家简单的介绍一下Service Bus,让大家能有一个初步了解。

该程序演示了Client向Service发送消息,service以相同的消息进行回应(Echo)。展示了Service Bus如何帮助在不同网络环境中的不同程序进行通信。

前置条件

为了使后续的教程能够顺利进行,请确保如下软件或组件已被安装:

· Microsoft .NET Framework 3.5 SP1

· Microsoft Visual Studio 2008 SP1 (or above)

· AppFabric SDK

 

请确保您已拥有一定的WCF编程经验,若没有,请浏览这里以快速的初步了解WCF。

最后请确保已创建了一个AppFabric项目和一个服务命名空间。请参考这里[](file:///C:/Users/t-liji/Desktop/lesson2-Windows%20Azure%20AppFabric%20入门教学%20-Echo.html#_msocom_1 "_msoanchor_1")

 

原理:

我们首先一下该Echo程序的运作原理。

 

 

步骤1,2,4,5是利用AppFabric中的Access Control Service(ACS)服务来确保安全性,这已超出了本篇教程的范畴,我们会在后续教程中讲解ACS的原理与运用。

我们主要关心步骤3和步骤6至9。步骤3为服务器程序与云端建立连接的过程。步骤6至9为客户端调用服务的过程。

Service Bus通过为服务提供了一套通用的命名规范简化了许多通信难题,在独立于网络拓扑和配置的节点之间提供直接或间接的通信。

Service Bus允许WCF应用程序监听公共网络地址,即使其位于NAT或网络防火墙后方。该功能使得应用程序的通信可以无关于其网络结构。使用Service Bus便无需编写与维护复杂的逻辑和代码来跨越不同的网络通信。

 

代码:

在了解了通信原理之后,我们来看看具体代码是如何编写的。

服务端:

1.在Visual Studio 2008中新建项目,请确保已选择 .NET framework 3.5并以Service命名,BasicSample为解决方案名创建Console Application

 

 说明: C:\Users\t-liji\Desktop\first\echo2.png

2.为Service项目添加程序集。右击Service项目,选择Add Reference.

加入System.ServiceModel以及Microsoft.ServiceBus.dll程序集。前者为WCF的核心程序集之一。后者能够在SDK中找到。

3.为Service项目添加IEchoContract服务契约。右击Service项目,Add->new Item

代码如下:

using System;

//应用WCF程序集

using System.ServiceModel;

//将接口定义为WCF的服务契约

namespace Service

{

 

  [ServiceContract(Name = "EchoContract", Namespace = "https://samples.microsoft.com/ServiceModel/Relay/")]

  public interface IEchoContract

  {

//定义了Echo操作契约,指明该方法为服务契约的一部分。

    [OperationContract]

    string Echo(string text);

 

  }

}

4.创建EchoService来实现IEchoContract服务契约。右击Service项目,Add->new Item

代码如下:

using System;

using System.ServiceModel;

namespace Service

{

//表明此类已实现WCF服务

[ServiceBehavior(Name = "EchoService", Namespace = "https://samples.microsoft.com/ServiceModel/Relay/")]

  public class EchoService: IEchoContract

  {

    public string Echo(string text)

    {

      Console.WriteLine("Echoing: {0}", text);

      return text;

    }

  }

}

 

5.通过AppFabric Service Bus来托管服务:

打开Program.cs,改为如下代码:

添加引用:

using System.ServiceModel;

using System.ServiceModel.Description;

using Microsoft.ServiceBus;

using Microsoft.ServiceBus.Description;

 

Main函数中:

static void Main(string[] args)

{

    Console.Title = "Service";

    Console.Write("Your Service Namespace Domain (e.g. sb://<YOUR-NAMESPACE>.servicebus.windows.net/): ");

    string serviceNamespaceDomain = Console.ReadLine();

    Console.Write("Your Issuer Name: ");

    string issuerName = Console.ReadLine();

    Console.Write("Your Issuer Secret: ");

    string issuerSecret = Console.ReadLine();

  

    // 基于服务命名空间来创建服务URI

    Uri address = ServiceBusEnvironment.CreateServiceUri("sb",

                  serviceNamespaceDomain, "EchoService");

 

    // 为端点(endpoint)创建凭据对象( credential object)

    TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();

    sharedSecretServiceBusCredential.CredentialType = TransportClientCredentialType.SharedSecret;

    sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerName = issuerName;

    sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerSecret = issuerSecret;

    // 创建会读取配置文件的服务宿主(service host)

    ServiceHost host = new ServiceHost(typeof(EchoService), address);

    // 为端点创建ServiceRegistrySettings 行为

    IEndpointBehavior serviceRegistrySettings = new ServiceRegistrySettings(DiscoveryType.Public);

 

    // 为配置文件中所有端点加入Service Bus凭据

    foreach (ServiceEndpoint endpoint in host.Description.Endpoints)

    {

        endpoint.Behaviors.Add(sharedSecretServiceBusCredential);

    }

    host.Open();

 

    Console.WriteLine("Service address: " + address);

    Console.WriteLine("Press [Enter] to exit");

    Console.ReadLine();

 

    // 关闭服务

    host.Close();

}

6.配置WCF服务

右击Service项目,Add->new Item

选择Application Configuration File。将App.config改为如下:

<configuration>

 

  <system.serviceModel>

    <services>

      <service name="Service.EchoService">

  <endpoint contract="Service.IEchoContract"

            binding="netTcpRelayBinding" />

 

      </service>

    </services>

  </system.serviceModel>

 

</configuration>

 

客户端:

7.与创建Service项目一样,创建一个新项目,命名为Client。

8.参考步骤2,为Client项目加入System.ServiceModel以及Microsoft.ServiceBus.dll程序集。

9.参考步骤3,添加IEchoContract服务契约,代码如下:

using System;

//应用WCF程序集

using System.ServiceModel;

//将接口定义为WCF的服务契约

namespace Client

{

 

  [ServiceContract(Name = "EchoContract", Namespace = "https://samples.microsoft.com/ServiceModel/Relay/")]

  public interface IEchoContract

  {

    [OperationContract]

    string Echo(string text);

 

  }

}

10.使用通过AppFabric Service Bus托管的WCF服务

打开Client项目的Program.cs

加入引用:

using System.ServiceModel;

using Microsoft.ServiceBus;

在Main函数中:

static void Main(string[] args)

{

    Console.Title = "Client";

    Console.Write("Your Service Namespace Domain (e.g. sb://<YOUR-NAMESPACE>.servicebus.windows.net/): ");

    string serviceNamespaceDomain = Console.ReadLine();

    Console.Write("Your Issuer Name: ");

    string issuerName = Console.ReadLine();

    Console.Write("Your Issuer Secret: ");

    string issuerSecret = Console.ReadLine();

 

    //基于服务命名空间来创建服务URI

    Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespaceDomain, "EchoService");

 

    //为端点(endpoint)创建凭据对象( credential object)

    TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();

    sharedSecretServiceBusCredential.CredentialType = TransportClientCredentialType.SharedSecret;

    sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerName = issuerName;

    sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerSecret = issuerSecret;

 

    // 创建读取配置文件的信道工厂( channel factory)

    ChannelFactory<IEchoContract> channelFactory = new ChannelFactory<IEchoContract>("RelayEndpoint", new EndpointAddress(serviceUri));

 

    // 应用Service Bus 凭证

    channelFactory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential);

 

    // 创建并打开客户端信道

    IEchoContract channel = channelFactory.CreateChannel();

    ((ICommunicationObject)channel).Open();

Console.WriteLine("Enter text to echo (or [Enter] to exit):");

    string input = Console.ReadLine();

    while (input != String.Empty)

    {

        try

        {

            Console.WriteLine("Server echoed: {0}", channel.Echo(input));

        }

        catch (Exception e)

        {

            Console.WriteLine("Error: " + e.Message);

        }

        input = Console.ReadLine();

    }

    ((ICommunicationObject)channel).Close();

    channelFactory.Close();

}

 

11.参考步骤6,为Client项目新建App.config,修改如下:

<configuration>

 <system.serviceModel>

  <client>

   <!-- Application Endpoint -->

     <endpoint name="RelayEndpoint"

                contract="Client.IEchoContract"

                binding="netTcpRelayBinding"/>

  </client>

 </system.serviceModel>

</configuration>

验证:

至此,代码已经创建完毕,我们已经可以进行调试了。

1.右击Service项目,Debug->Start new Instance。(按F5也可)

 

按照Console提示输入您在Windows Azure platform AppFabric portal处所注册得到的信息。

Service Namespace Domain,Issuer Name 和Issuer Key的具体位置请参照下图。

 说明: C:\Users\t-liji\Desktop\first\issuer.png

 

 

 

 

2.右击Client项目,Debug->Start new Instance启动另一调试实例,同样按照Console提示输入信息。

最终效果如图:

说明: C:\Users\t-liji\Desktop\first\echo5.png

探析:

 

本示例简单的展示了如何通过Service Bus暴露服务以便让客户端访问。假设我们在公司内部运行服务器端程序,我们能够在任何可以访问Internet的机器上运行客户端程序。无论客户端身处何种网络结构,都能通过该URI访问到服务。在本例中该URI会成为如下形式:sb://<serviceNamespace>.servicebus.windows.net/EchoService/

Service Bus为我们应用程序之间的通信提供了桥梁,我们无需编写和维护复杂的代码。

本示例程序中还有另外一个重要概念便是程序通信时的绑定(binding)方式。这原本是WCF中的概念,但是ServiceBus对其进行了扩展,本例使用的NetTcpRelayBinding便是拓展的binding之一。NetTcpRelayBinding能够使你暴露出通过URI便能访问的端点。当使用NetTcpRelayBinding 的端点打开时,其URI便被注册于ServiceBus,任何使用相同类似配置的授权客户便能向该URI发送信息。这样,Service Bus便成为了那2个端点之间的中转。

目前为止,我们的教程都是基于Azure付费账户的。在下一篇教程中我们会介绍LABS环境。LABS提供了免费的使用环境。这对于国内用户和开发者来说会带来极大的便利。敬请期待我们的下一篇教程。好了,大家赶快动手试一下,进入奇妙的AppFabric世界吧!