Producing comments

Having written the code to display comments, it's now time to craft the bits to create them.

We've already seen the changes to our template adding an HTML form to write a comment. Let's code the corresponding controller in the comments subpackage, as follows:

    @Controller 
    public class CommentController { 
 
      private final RabbitTemplate rabbitTemplate; 
 
      public CommentController(RabbitTemplate rabbitTemplate) { 
        this.rabbitTemplate = rabbitTemplate; 
      } 
 
      @PostMapping("/comments") 
      public Mono<String> addComment(Mono<Comment> newComment) { 
        return newComment.flatMap(comment -> 
         Mono.fromRunnable(() -> rabbitTemplate 
           .convertAndSend( 
             "learning-spring-boot", 
             "comments.new", 
             comment))) 
           .log("commentService-publish") 
           .then(Mono.just("redirect:/")); 
      } 
 
    } 

The code can be explained as follows:

  • It's the first class we have put in the new comments subpackage.
  • The @Controller annotation marks this as another Spring controller.
  • It contains a RabbitTemplate initialized by constructor injection. This RabbitTemplate is created automatically by Spring Boot when it spots spring-amqp on the classpath.
  • The @PostMapping("/comments") annotation registers this method to respond to the form submissions that we added earlier in the template with th:action="@{'/comments'}".
  • Spring will automatically convert the body of the POST into a Comment domain object. Additionally, since we are using WebFlux, deserializing the request body is wrapped in a Mono, hence that process will only occur once the framework subscribes to the flow.
  • The incoming Mono<Comment> is unpacked using flatMap and then turned into a rabbitTemplate.convertAndSend() operation, which itself is wrapped in Mono.fromRunnable.
  • The comment is published to RabbitMQ's learning-spring-boot exchange with a routing key of comments.new.
  • We wait for this to complete with then(), and when done, return a Spring WebFlux redirect to send the webpage back to the home page.

Time out. That bullet point about the RabbitMQ exchange and routing key may have sounded a bit complex.

The comment is published to RabbitMQ's learning-spring-boot exchange with a routing key of comments.new.

We need to take this apart to understand the basics of AMQP a little better.

..................Content has been hidden....................

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