Communicating Between Service Fabric Micro-Services

When you are building a micro-service architecture then you have many internal services and a service implementing the API Gateway pattern acts as the one API surface for outsiders communicating with your application. The Gateway API needs to forward requests to your internal micro-services. To do this in Microsoft’s Service Fabric, you can use the Service Fabric Reverse Proxy or ServicePartitionResolver. Under the hood, Service Fabric Naming Service and other services are monitoring each instance and endpoint. Using the Reverse Proxy, you can communicate with other services without hard coding the endpoints. It is important not to hard code endpoints because when you start to scale the application you will want it to dynamically use different instances of the same service, like a load balancer.

This is an example of a ASP.NET Core Web API controller Post() method in the Gateway API that is resolving an endpoint using the ServicePartitionResolver to get an endpoint to call for the SampleOAuthService micro-service. Then it forwards the request and returns the response. In a production app, you can do more validation and rate limiting in the Gateway API Post() method.

[HttpPost]
[Route(“api/oauth/token”)]
public async Task<IActionResult> Post()
{
var resolver = ServicePartitionResolver.GetDefault();
var cancellationToken = new System.Threading.CancellationToken();
var p = await resolver.ResolveAsync(new Uri(“fabric:/SampleOAuthService/IdentityWebApi”), new ServicePartitionKey(), cancellationToken);
     var reader = new StreamReader(this.Request.Body);
var body = reader.ReadToEnd();
var content = new StringContent(body, System.Text.Encoding.UTF8, “application/x-www-form-urlencoded”);
     var http = new HttpClient();
JObject addresses = JObject.Parse(p.GetEndpoint().Address);
string primaryReplicaAddress = (string)addresses[“Endpoints”].First();
     var url = primaryReplicaAddress + “/oauth/token”;
var response = await http.PostAsync(url, content);
var responseContent = await response.Content.ReadAsStringAsync();
JObject responseObject = JObject.Parse(responseContent);
     return new OkObjectResult(responseObject);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s