I am trying to use Zuul filter to do dynamic routing. I have an application that runs in Spring Boot. This application exposes two services.
@PostMapping("/update")
public String updateBook(Book book) {
return " Book Updated";
}
@PostMapping("/add")
public String addBook(Book book) {
return " Book Added";
}
Application.properties for this application is
spring.application.name=book
server.port=8090
In my zuul filter, I am redirecting any request to either /update or /add based on some logic.
Zuul configuration is as below.
zuul.routes.books.url=http://localhost:8090
ribbon.eureka.enabled=false
server.port=8080
Redirect is done using the below code in run()
in a filter class which extends ZuulFilter
@Override
public Object run() {
RequestContext context = RequestContext.getCurrentContext();
String requestBody = CharStreams.toString(context.getRequest().getReader());
Gson gson = new Gson();
Book book = gson.fromJson(requestBody, Book.class);
if (book.getType().equals("update")) {
context.setRouteHost(new URL("http://localhost:8090/update"));
}
else {
context.setRouteHost(new URL("http://localhost:8090/add"));
}
return null;
}
When I invoke
curl -i -X POST -H "Content-Type:application/json" -d "{\"id\":\"1\", \"name\":\"Book1\", \"type\":\"update\"}" http://localhost:8080/books/add
I expect it should redirect to the /update service since type is passed as update. But I see that it is the add service that is being invoked. The setRouteHost code is beingg executed, but redirection is not happening.
Is there something I am missing? Any pointers would be appreciated.
Thanks
I was able to get this working by using the below code.