Wednesday, June 12, 2019

Microservices - Api Gateway

Greetings!

I was too busy past couple of days and lost my way of continuing Microservices series. So I decided to add simple dummy services service-a and service-b. Other than that, there is no change except the github repo.

https://github.com/slmanju/simple-microservice

In Microservices architecture we are dealing with many apis which work along or work with other services. Imagine that we are going to create a mobiile client using these client it will be very difficult to manage all services by that client. Or, imagine we expose our apis so that anyone can create their own client.
This is a good place to introduce a another service which act as a gateway to all other services. Third party clients will know only about this api.
Not only this, we can solve some other problems using Api Gateway.

  • Single entry point to all the services.
  • Common place to log request and responses.
  • Authentication users in single place.
  • Rate limits.
  • Add common filters.
  • Hide internal services.


To create our api gateway, we are going to use Netflix Zuul.
Just like other Spring Boot libraries, this is also just a matter of adding the library and add related configurations.

First of all let's generate the project by adding necessary dependencies.
<<IMAGE>>

You can this block in maven pom
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>

Then we need to mark this service as our Api gateway by adding @EnableZuulProxy.
@EnableEurekaClient
@EnableZuulProxy
@SpringBootApplication
public class ApiGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }

}

Now our gateway is ready. Let's add the port the service name in application yaml file.
server:
  port: 7060

spring:
  application:
    name: api-gateway

Then we need to tell where is the discovery service by adding Eureka properties.
eureka:
  client:
    registerWithEureka: true
    fetchRegistry: true
    serviceUrl:
      defaultZone: http://localhost:7050/eureka/

If we start our services now, others services are available by their service name.
http://localhost:7060/service-a/

Let's override this and add our own name.
zuul:
  ignored-services: "*"
  routes:
    service-a:
      path: /api/service-a/*
      serviceId: service-a

Now our service is avaible at http://localhost:7060/api/service-a/


No comments:

Post a Comment