Routing requests to services
In previous recipes, we focused on having your monolith route requests to services. This technique is a good start since it requires no client changes to work. Your clients still make requests to your monolith and your monolith marshals the request to your microservices through its controller actions. At some point, however, to truly benefit from a microservices architecture, you'll want to remove the monolith from the critical path and allow your clients to make requests to your microservices. It's not uncommon for an engineer to expose their organization's first microservice to the internet directly, usually using a different hostname. However, this starts to become unmanageable as you develop more services and need a certain amount of consistency when it comes to monitoring, security, and reliability concerns.
Internet-facing systems face a number of challenges. They need to be able to handle a number of security concerns, rate limiting, periodic spikes in traffic, and so on. Doing this for each service you expose to the public internet will become very expensive, very quickly. Instead, you should consider having a single edge service that supports routing requests from the public internet to internal services. A good edge service should support common features, such as dynamic path rewriting, load shedding, and authentication. Luckily, there are a number of good open source edge service solutions. In this recipe, we'll use a Netflix project called Zuul.
How to do it...
- Create a new Spring Boot service called
Edge Proxy
with a main class calledEdgeProxyApplication
. - Spring Cloud includes an embedded Zuul proxy. Enable it by adding the
@EnableZuulProxy
annotation to yourEdgeProxyApplication
class:
package com.packtpub.microservices; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @EnableZuulProxy @SpringBootApplication public class EdgeProxyApplication { public static void main(String[] args) { SpringApplication.run(EdgeProxyApplication.class, args); } }
- Create a file called
application.properties
undersrc/main/resources/
with the following contents:
zuul.routes.media.url=http://localhost:8090 ribbon.eureka.enabled=false server.port=8080
In the preceding code, it tells zuul
to route requests to /media
to a service running on port 8090
. We'll touch on that eureka
option in later chapters when we discuss service discovery, for now just make sure it's set to false
.
At this point, your service should be able to proxy requests to the appropriate service. You've just taken one of the biggest steps toward building a microservices architecture. Congratulations!