Search code examples
javarestsocketsinvocation

Chaining of services - Java


At the moment I'm using multiple REST services to process my data. A workflow would be like this:

User requests the speed of a car: Ask the SpeedService the most recent speed => SpeedService requests the latests positions of the car from the PositionService and the PositionService achieves this by calling the DatabaseService in order to get the raw unprocessed data from the car. However the part where I'm having issues is calling a service withing another service. I've achieved this for now by making uses of the invocation api.

Example:

Client client = ClientBuilder.newClient();
        WebTarget target = client.target("http://mylocalRestserver.example/webresources/").path("speed");
        target = target.queryParam("carId", carId);
        Invocation invocation = target.request(MediaType.APPLICATION_JSON).buildGet();
        Speed speed = new Genson().deserialize(invocation.invoke(String.class), Speed.class);
        return speed;

However whenever I try to simulate concurrent users - running multiple curl queries - the REST service breaks due to SocketTimeouts, I assume because multiple requests are sent on the same serversocket? Is there any way to achieve this "chaining of services"?


Solution

  • Your idea is sound but cannot be implemented with such a naive approach.

    What you are trying to achieve is location transparency while keeping the system responsive, which is not an easy task.

    There are big frameworks that deal with this problem, AKKA comes to mind.

    If your objective is just separation of concerns (each service deals with is part of the problem and invokes other services to get what it needs), you can just use the relevant classes without making http request from the server to itself.

    If instead you want to be able to distribute your services across several nodes you should rely on frameworks like akka, doing it yourself is an unfeasible task.