Search code examples
spring-bootrabbitmqrpcspring-amqpspring-rabbit

Can Spring Boot be configured to act as both client and server (mesh topology) with RabbitMQ RPC?


I have 2 apps developed with spring boot:

App1:

  • exposes an API for app2, for example /api/members
  • makes a call to app2 in order to retrieve weather details, for example /api/weather

App2:

  • exposes an API for app1, /api/weather
  • makes a call to app1 in order to retrieve member details, /api/members

The communication between them is made using HTTP at the moment. Is there a way to configure rabbitMQ inside spring boot to act as a consumer on an exchange, and a producer on another one? Would this be ok from the architectural POV? I could not find any articles related to this. Any links/ examples would be greatly appreciated.


Solution

  • I figured this one out:

    This is the RabbitMQ config file:

    @Configuration
    class RabbitCfg {
      @Bean
      fun queue() = Queue("queueName")
    
      @Bean
      fun exchange() = DirectExchange("exc")
    
      @Bean
      fun binding(exchange: DirectExchange, queue: Queue) = BindingBuilder.bind(queue).to(exchange).with("routeKey")
    
      @Bean
      fun jsonMessageConverter() = Jackson2JsonMessageConverter(ObjectMapper())
    }
    
    

    Afterwards I am able to call from app1:

    val response = rabbitTemplate.convertSendAndReceive(exchange.name, "otherRouteKey", req) as MyObj
    

    and handle requests from app2 in the same spring boot project:

    @Service
    @RabbitListener(queues = ["queueName"])
    class Receiver {
    
      @RabbitHandler
      fun handleMenuMessage(obj: MyObj) = OtherObj()
    
      ...
    }
    

    The only condition required is that both apps are configured on the same exchange, with different "routeKey" values.