In my application a user creates a post which gets persisted in the db + published to a Spring amqp queue
When the user creates a post flow hits the controller
@RequestMapping(value="/createPost", method=RequestMethod.POST, consumes = "application/json",
produces = "application/json")
public @ResponseBody Post createUserPost(@RequestBody(required=false) Post post, Principal principal){
this.userService.persistPost(post);
logger.info("post persistance successful");
publishService.publishUserPosts(post);
return post;
}
There are two services persistPost
& publishUserPosts
in different Service classes called in the controller.
Publish Service
@Transactional
public void publishUserPosts(Post post){
try{
logger.info("Sending user post to the subscribers");
amqpTemplate.convertAndSend(post);
}catch(AmqpException e){
throw new MyAppException(e);
}
}
The problem is both service calls are running under different transactions. If the PublishPost
transaction fails the post is still persisted in the db.
To bring both the services under a single transaction I've changed the code & injected the persistPost
service in PublishPost
class.
@Transactional
public void publishUserPosts(Post post){
try{
userService.persistPost(post);
logger.info("post persistance successful");
logger.info("Sending user post to the subscribers");
amqpTemplate.convertAndSend(post);
}catch(AmqpException e){
throw new MyAppException(e);
}
}
My question
Is this the best approach to achieve multiple services under a single transaction or I can do better with some other approach?