The compensate phase

In the compensate phase, the LRA coordinator invokes the method annotated with @Compensate and performs the business operations needed to make the business operation consistent, in terms of the data status after a condition that determines the operation as failed.

In our scenario, the method will set the status of the offer to "REFUSED" and the status of the football player to "Free". We have decided to set "Free" and not null, in order to show that the record is updated by a method invoked by the LRA coordinator.

The following code is required to do so:

/**
* LRA compensate method: it sets the final status of the football player offer
* and football player based on a failed response of the send offer method.
*
* @param lraId The Long Running Action identifier needed to retrieve
* the record on which perform the operation.
* @return the Response of the operation.
*/
@PUT
@Path("/compensate")
@Produces(MediaType.APPLICATION_JSON)
@Compensate
public Response compensateWork(@HeaderParam(LRAClient.LRA_HTTP_HEADER) String lraId) {

LOG.log(Level.INFO, "Start method compensateWork: I'm in LRA compensate phase");

String lraIdParameter = lraId.substring(lraId.lastIndexOf('/') + 1);

LOG.log(Level.FINE, "Value of lraIdParameter {0}", lraIdParameter);

LOG.log(Level.FINE, "Setting the offer as REFUSED ...");
// Set the offer to REFUSED
FootballPlayerOffer fpo = footballPlayerOfferTarget.path("lraId/"
+ lraIdParameter).request().get(
new GenericTypeFootballPlayerOfferImpl());

fpo.setStatus("REFUSED");

footballPlayerOfferTarget.path(fpo.getId().toString()).request().put(
Entity.entity(fpo, MediaType.APPLICATION_JSON_TYPE));

LOG.log(Level.FINE, "Set the offer as REFUSED ...");

FootballPlayer player = footballPlayerTarget.path("lraId/"
+ lraIdParameter).
request().get(new GenericTypeFootballPlayerImpl());

LOG.log(Level.FINE, "Got football player {0}", player);

player.setStatus("Free");
player.setLraId(null);

LOG.log(Level.FINE, "Changing football player status ...");

footballPlayerTarget.path(player.getId().toString()).request().put(
Entity.entity(player, MediaType.APPLICATION_JSON_TYPE));

LOG.log(Level.INFO, "End method compensateWork: LRA compensate phase terminated");

return Response.ok().build();
}

The main element of the method is the @Compensate annotation; in this way, the method is considered a participant of the LRA, and the LRA coordinator will automatically invoke it in the case of a failure of the operation that starts the LRA context.

To run the microservice, you should launch the following command:

$ java -jar target/football-player-market-microservice-lra-thorntail.jar -Dlra.http.port=8580   
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset