NET Framework System Web Services Description Discovery Protocols
. NET Framework Классы System. Web Services Description Discovery Protocols UI Html. Controls Caching Configuration Security Session. State OLEDB Design (C) Сафонов В. О. 2013 Form Button Message. Box List. Control Web. Controls System. Data Collections Configuration Diagnostics Globalization System. Windows. Forms SQLTypes IO Net Reflection Resources System. Drawing 2 D Imaging XSLT XPath System Security Service. Process Text Threading Printing Text System. Xml Serialization Runtime Interop. Services Remoting Serialization
Инфраструктура Web-сервисов. NET Request. vsdisco Discovery Return disco (XML) Web Service Client Request WSDL Description Return WSDL (XML) Request. asmx Protocol Return response (XML) (C) Сафонов В. О. 2013 Web Service
Пример реализации Web-сервиса. NET <%@ Web. Service Language=“C#“ Class=“Math. Service“ %> using System; using System. Web. Services; public class Math. Service { [Web. Method] public int Subtract(int a, int b) { return a - b; } public int Subtract_vs(int a, int b) { return b - a; } } (C) Сафонов В. О. 2013
WSDL Абстрактная структура WSDL-элементов service_1 port_B port_C message service_2 port_D port_A message port type (C) Сафонов В. О. 2013 (C) Сафонов В. О. 2009 12
Пример WSDL-файла <definitions name=“service. Name“> <import namespace=“http: //namespace. Path“ location=“http: //path/file. Name. wsdl“> <port. Type name=“service. Name. Port. Type“> <operation name=“op. Name“> <input message=“msg. Name. Input“ /> <output message=“msg. Name. Output“ /> </operation> </port. Type> <binding name=“service. Name. Soap. Binding“> <soap: operation soap. Action=“http: //. . . “ /> </binding> <service name=“service. Name“> <port name=“service. Name. Port“ binding=“binding. Name“> <soap: address location="http: //. . . " /> </port> </service> </definitions> (C) Сафонов В. О. 2013
Пример (. aspx) <%@ Import Namespace=“Math. Service. Space“ %> <script language=“C#“ runat="server"> public void Submit_Click(Object S, Event. Args E) { service. Add(operand 1, operand 2); . . . </script>. . . <input On. Server. Click=“Submit_Click“ runat="server". . . > (C) Сафонов В. О. 2013
Архитектура Windows Azure Cloud Application Windows Azure Compute Storage Fabric Controller Windows Azure Fabric (C) Сафонов В. О. 2013 Network
Модель сервисов: Определение сервисов Файл Service. Definiton. csdef определяет общую структуру сервиса: vmsize: ядра CPU (1 – 8) и память для виртуальной машины VM (1. 7 – 15 GB) full/partial trust: поддерживается исполнение native-кода Endpoint: внутренние и внешние точки взаимодействия (http, https, tcp) Local. Storage: временная память на сервере, на котором исполняется объект Configuration. Settings: имена параметров конфигурации Service Definition обрабатывается во время развертывания приложения. <Service. Definition name="My. Service" …> <Web. Role name="My. Web. Role" enable. Native. Code. Execution="false" vmsize="Medium"> <Input. Endpoints> <Input. Endpoint name="Http. In" protocol="http" port="80" /> </Input. Endpoints> <Configuration. Settings> <Setting name="name 1" /> … </Configuration. Settings> </Web. Role> </Service. Definition> (C) Сафонов В. О. 2013
Модель сервисов: Конфигурация сервисов Файл Service. Configuration. csdef указывает число экземпляров каждой роли определяет значения для установок конфигурации. Service Configuration может быть изменена во время выполнения. <Service. Configuration service. Name="My. Service" xmlns= "…"> <Role name="My. Web. Role"> <Instances count="3" /> <Configuration. Settings> <Setting name="name 1 " value="value 1" /> </Configuration. Settings> </Role> </Service. Configuration> (C) Сафонов В. О. 2013
Классы Windows Azure Role API Current. Role. Instance Roles On. Start() On. Stop() Run() On. Start() My. Worker. Rol On. Start() e Roles My. Web. Role Get. Configuration. Setting. Value() Request. Recycle() Changed (Event) Changing (Event) Stopping (Event) Run() * (C) Сафонов В. О. 2013 Role Instances Names Role. Instance Id Role Fault. Domain Update. Domain Instance. Endpoints Current. Role. Instance Role. Environment Basic. Entry. Point
Реализация ролей Определить класс-потомок Role. Entry. Point и перегрузить методы жизненного цикла. Обычно перегружается метод On. Start() Регистрируется обработчик, который прослушивает изменения в конфигурации учетной записи облачной памяти. Когда обнаруживается изменение, роль повторно стартуется (переиспользуется). public class My. Role: Role. Entry. Point { public override bool On. Start() { Cloud. Storage. Account. Set. Configuration. Setting. Publisher( (config. Name, config. Setter) => { config. Setter(Role. Environment. Get. Configuration. Setting. Value(config. Name)); Role. Environment. Changed += (sender, arg) => { if (arg. Changes. Of. Type<Role. Environment. Configuration. Setting. Change>(). Any((change) => (change. Configuration. Setting. Name == config. Name))) { if (!config. Setter(Role. Environment. Get. Configuration. Setting. Value(config. Name))) Role. Environment. Request. Recycle(); }; // handler for Changed event }); // Set. Configuration. Setting. Publisher return base. On. Start(); } } (C) Сафонов В. О. 2013
Взаимодействие между ролями на основе WCF/TCP (1) Реализация сервиса xxx [Service. Contract(Namespace="…")] public interface ICalculator { [Operation. Contract] double Add(double a, double b); } public class Calculator. Service : ICalculator { public double Add(double a, double b) { return a + b; } } § Конфигурация worker-роли § Добавление внешних или внутренних коммуникационных точек <Service. Definition name="Calc. Service". . . > <Worker. Role name="Calc. Role" enable. Native. Code. Execution="true"> <Endpoints> <Input. Endpoint name="Calc. Service. EP" port="5000" protocol="tcp" /> <Internal. Endpoint name="My. Internal. EP" protocol="tcp"/> </Endpoints> </Worker. Role> </Service. Definition> (C) Сафонов В. О. 2013
Взаимодействие между ролями на основе WCF/TCP (2) § Хостинг WCF-сервиса External App Windows Azure Role Instance Load Balancer net. tcp: //my. Project. cloudapp. net: 5000/Calc. Service Current. Role. Instance. Endpoints["Calc. Service"] public class Worker. Role : Role. Entry. Point { private Service. Host service. Host; public override void Run() { this. service. Host = new Service. Host(typeof(Calc. Service)); } } Net. Tcp. Binding binding = new Net. Tcp. Binding(Security. Mode. None); Role. Instance. Endpoint external. End. Point = Role. Environment. Current. Role. Instance. Endpoints["Calc. Service. EP"]; this. service. Host. Add. Service. Endpoint( typeof(ICalc. Service), binding, String. Format("net. tcp: //{0}/Calc. Service", external. End. Point. IPEndpoint)); // hostname and port (C) Сафонов В. О. 2013
Взаимодействие между ролями на основе WCF/TCP (3) § Реализация клиента Net. Tcp. Binding binding = new Net. Tcp. Binding(Security. Mode. None, false); using (Channel. Factory<ICalc. Service> cf = new Channel. Factory<ICalc. Service>(binding, "net. tcp: //5000/Calc. Service")) { ICalc. Service calc. Proxy = cf. Create. Channel(); double sum = calc. Proxy. Add(1, 2); } При использовании внутренних коммуникационных точек отправитель должен выполнять балансировку загрузки вручную. Используйте Role. Environment. Roles[“Target. Role”] для поиска этих коммуникационных точек foreach (Role. Instance ri in Role. Environment. Roles["Calc. Role"]. Instances) { Role. Instance. Endpoint ep = ri. Instance. Endpoints["My. Internal. EP"]; string address = String. Format("net. tcp: //{0}/My. Service", ep. IPEndpoint); var cf = new Channel. Factory<IMy. Service>(binding, address); … } (C) Сафонов В. О. 2013
Взаимодействие между экземплярами ролей Web Role Instance Cloud. Queue Message Cloud. Queue. Client queue. Client = storage. Account. Create. Cloud. Queue. Client(); Cloud. Queue queue = queue. Client. Get. Queue. Reference( "my. Queue"); queue. Create. If. Not. Exist(); queue. Add. Message( new Cloud. Queue. Message( message. Content)); (C) Сафонов В. О. 2013 Queue Cloud. Queue Message Worker Role Instance public class Worker. Role : Role. Entry. Point { public override void Run() {. . . Cloud. Queue queue = queue. Client. Get. Queue. Reference("my. Queue"); queue. Create. If. Not. Exist(); // create queue while (true) { Cloud. Queue. Message msg = queue. Get. Message(); if (msg != null) { Process. Message(msg); queue. Delete. Message(msg); } else Thread. Sleep(1000); } } }
- Slides: 36