A basic example
In the java world the common approach is to use Spring with a circuit-breaker, in most cases this would be Hystrix. A short example would be:But as you can see, even for simple mappings that don't have a fallback or other special mechanism provided by Hystrix, you have to write a bunsh of code. For each mapping there has to be a method in the RestController class, a service method in form of an interface and an implementation and at last all required models. For small apis this is not really a problem, but when the api is growing it becomes harder and harder to maintain.
Our solution
We thought it would be easier to create annotations that simplifies the mapping process. With them you can define which url of the api-gateway is mapped to which url on another service. If you need fallback methods it is still possible to define them like in the example above. Our implementation of such annotations looks like this:Now you are able to concentrate on the implemenation of methods in the RestController, that do more than just mapping one endpoint to another.
The implementation
Now you might be interested how we got that work. First we created our own implementation of the abstract class RequestMappingInfoHandlerMapping. There we create a mapping for each annotation we find and apply a handler to it:The handler then gets called when a client requests an url and it creates and executes a hystrix command. This command needs a unique name in order to use a seperate threadpool for each endpoint url of the api-gateway (the default behaviour of using the simple class name is not sufficient because all enpoints use the same class). The command then simply propagates the request forward to the desired service:
And that's all. Only ensure that you include the right dependencies to get this work.
No comments:
Post a Comment