views:

10

answers:

1

I'm using RabbitMQ and trying to refactor my current native java implementation to using the Spring AMQP abstraction.

Declaration of exchanges, queues and their binding using the Spring library is via the AMQPAdmin interface, but I'm not sure when this sort of configuration should happen.

I have a web application that uses Rabbit to produce messages. And another app that consumes these messages. Shocker :)

But when show the declaration of the exchanges/queues take place?

Do I deploy the AMQPAdmin with the web applications and do exchange/queue administration within constructors of producers and consumers?

Declaration of these things are a one off, the broke doesn't need to know about them again, so any code would be a NOOP on subsequent executions.

Do I create a separate application for administration of the broker?

What is the current thinking or best practices here?

A: 

It would appear that very few people are using Spring's AMQP M1 release, so I will answer my own question with what I've done.

In the producer's constructor I declare the exchange. Then set the exchange on the RabbitTemplate. I also set the routing key on the RabbitTemplate as the queue name, but that isn't required, but it was the route I would be using.

@Service("userService")
public class UserService {
    private final RabbitTemplate rabbitTemplate;

    @Autowired
    public UserService(final RabbitAdmin rabbitAdmin,
                       final Exchange exchange,
                       final Queue queue,
                       @Qualifier("appRabbitTemplate") final RabbitTemplate rabbitTemplate) {

        this.rabbitTemplate = rabbitTemplate;

        rabbitAdmin.declareExchange(exchange);
        rabbitTemplate.setExchange(exchange.getName());
        rabbitTemplate.setRoutingKey(queue.getName());  
    }


    public void createAccount(final UserAccount userAccount) {
        rabbitTemplate.convertAndSend("Hello message sent at " + new DateTime());
    }
}

In the consumer's constructor I declare the queue and create the binding.

public class Consumer implements ChannelAwareMessageListener<Message> {

    public Consumer(final RabbitAdmin rabbitAdmin, final Exchange exchange, final Queue queue) {
        rabbitAdmin.declareQueue(queue);

        rabbitAdmin.declareBinding(BindingBuilder.from(queue).to((DirectExchange) exchange).withQueueName());
    }

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {

        System.out.println(new String(message.getBody()));

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
    }
}

Although the constructors may be run many times, RabbitMQ only declares the exchange, queue and bindings once.

If you need the whole source for this little example project, ask, and I'll put it up somewhere for you.

dom farr