Skip to main content

Care este cel mai rapid mod prin care putem consuma un serviciu REST

In ultima perioada din ce în ce mai multe servicii publice în format REST au apărut pe piaţa.
O problema destul de neaşteptata apare pe partea de client:
Cum sa consumam un serviciu REST?
Din start, .NET ne oferă doua variante destul de simple pentru a putea utiliza un serviciu REST:
  • WCF Client - Service Contract;
  • WebRequest;
Pentru a putea consuma un serviciu folosindu ne de WCF avem nevoie sa ne declaram un contract (ServiceContract) în care sa specificam operaţiile care ne sunt puse la dispoziţie.
[ServiceContract()]
[XmlSerializerFormat()]
public interface ICarClient
{
[OperationContract]
[WebGet(
ResponseFormat = WebMessageFormat.Xml,
UriTemplate = "Car/{id}?userkey={userKey}")]
Car GetCar(string id,string userKey);
}

La acest nivel am definit prin atributul WebGet locaţia acestei resurse (UriTemplate) relativa la adresa setata în fişierul de configurare. Urmatorul pas este sa ne configuram un endpoint in fisierul de configurare de forma:
<system.servicemodel>
<client>
<endpoint address="http://www.carCollection.com/" binding="webHttpBinding" behaviorconfiguration="CarRestBehavior" contract="CarEx.ICarClient" name="CarRestEndpoint">
</endpoint>
<behaviors>
<endpointbehaviors>
<behavior name="CarRestBehavior">
<webhttp>
</webhttp>
</behavior>
</endpointbehaviors>
</behaviors>

Este foarte important la acest pas sa configuram comportamentul la endpoint şi sa îl setam pe "webHttp".
Odată ce am făcut acest lucru putem sa ne cream un proxy prin intermediul la ChannelFactory, iar mai departe sa apelam serviciul dat.
ChannelFactory factoryCar = new ChannelFactory("CarRestEndpoint");
ICarClient carClientProxy = factoryCar.CreateChannel();
Car car = carClientProxy.GetCar("1","userKey");
Nu vreau sa intru în mai multe detalii pe partea de configurare. In cazul in care avem noroc ca serviciul pe care vrem sa îl consumam are definit un WSDL (Web Service Definition Language), atunci ajunge doar sa adaugăm în proiect o referința la serviciu ("Add Service Referince").
Pentru a putea consuma un serviciu REST putem sa folosim și WebRequest (care este mult mai ușor de folosit).
WebRequest request = WebRequest.Create("http://www.carCollection.com/Car/1?userKey=userKey");
WebResponse webResponse = request.GetResponse();
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Car));
Car car = (Car)xmlSerializer.DeserializewebResponse.GetResponseStream());
Este destul de simplu, este nevoie sa specificam adresa și sa facem un request. Răspunsul o sa îl primim ca un stream pe care trebuie apoi sa îl deserializam. Partea de procesare stream și deserializare trebuie sa o facem manual.
Si acuma apare o noua întrebare, care m-a făcut sa scriu acest post:
Care din cele doua mecanisme credeți ca este mai rapid?
La prima strigare am spus ca WCF Client. In spate avem o colecție de librarii dezvoltate în timp. Acestea ar trebuii sa fie optimizate și sa meargă excelent, dar iată ce rezultate am obținut în urma testelor:
  • WCF Client: 35s
  • Web Request: 11s
La prima vedere nu am înțeles foarte bine cauza dar apoi am găsit mai multe cauze pentru acest lucru.
Un apel de tip web request este extrem de simplu, iar WCF este mult prea complicat pentru ce avem nevoie noi. Deșii oferă o multitudine de opțiuni, de foarte multe ori pentru un web request noi folosim doar 1% din cea ce ne oferă, caz în care încărcam multe librarii fără nici un rost.
Prin WCF suntem nevoiți sa trecem printr-un flow extrem de complex care implica mecanisme costisitoare din punct de vedere a timpului precum reflection.
Asta nu inseamna ca o sa ne fie ușor sa folosim Web Reques, pot sa apară cazuri când este mult mai ușor sa lucram cu ChannelFactory (WCF) si nu cu web request dar din punct de vedere a timpului, un web request o sa fie mereu mai rapid.

Comments

  1. 35s pentru un singur apel?

    WCF e logic sa aiba un oarecare overhead, dar cel mai adesea e neglijabil comparativ cu delay-ul dat de faptul ca e un remote call, in Internet, peste o conexiune cu un bandwidth limitat si un anume latency, la care se adauga cel mai adesea si un access la db cel putin..

    Cu WebRequest va trebui sa faci manual deserializarea, partea de security, session etc..

    ReplyDelete
  2. Nu este vorba de un sigur apel. Erau 500 de apeluri spre un anumit serviciu. Testele le-am făcut împreuna și le-am repetat de 2-3 ori, timpii pe care i-am obținut fiind asemănători.

    ReplyDelete

Post a Comment

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(

Azure AD and AWS Cognito side-by-side

In the last few weeks, I was involved in multiple opportunities on Microsoft Azure and Amazon, where we had to analyse AWS Cognito, Azure AD and other solutions that are available on the market. I decided to consolidate in one post all features and differences that I identified for both of them that we should need to take into account. Take into account that Azure AD is an identity and access management services well integrated with Microsoft stack. In comparison, AWS Cognito is just a user sign-up, sign-in and access control and nothing more. The focus is not on the main features, is more on small things that can make a difference when you want to decide where we want to store and manage our users.  This information might be useful in the future when we need to decide where we want to keep and manage our users.  Feature Azure AD (B2C, B2C) AWS Cognito Access token lifetime Default 1h – the value is configurable 1h – cannot be modified

What to do when you hit the throughput limits of Azure Storage (Blobs)

In this post we will talk about how we can detect when we hit a throughput limit of Azure Storage and what we can do in that moment. Context If we take a look on Scalability Targets of Azure Storage ( https://azure.microsoft.com/en-us/documentation/articles/storage-scalability-targets/ ) we will observe that the limits are prety high. But, based on our business logic we can end up at this limits. If you create a system that is hitted by a high number of device, you can hit easily the total number of requests rate that can be done on a Storage Account. This limits on Azure is 20.000 IOPS (entities or messages per second) where (and this is very important) the size of the request is 1KB. Normally, if you make a load tests where 20.000 clients will hit different blobs storages from the same Azure Storage Account, this limits can be reached. How we can detect this problem? From client, we can detect that this limits was reached based on the HTTP error code that is returned by HTTP