← Back to the chapter · Previous detail · Next detail →

Technical detail · AMQP Operations: Deployment and Broker Health

Java publisher with RabbitMQ Java Client

import com.rabbitmq.client.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class AMQPPublisher implements AutoCloseable {
    private final Connection connection;
    private final Channel channel;
    private final String exchange;
    private final ObjectMapper mapper = new ObjectMapper();

    public AMQPPublisher(String host, String exchange)
            throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(host);
        factory.setRequestedHeartbeat(60);

        this.connection = factory.newConnection();
        this.channel = connection.createChannel();
        this.exchange = exchange;

        // Enable publisher confirms
        channel.confirmSelect();

        // Declare durable topic exchange
        channel.exchangeDeclare(exchange, "topic", true);
    }

    public boolean publish(String routingKey, Object message,
            String messageId) throws Exception {
        AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
            .deliveryMode(2)  // Persistent
            .contentType("application/json")
            .messageId(messageId)
            .build();

        byte[] body = mapper.writeValueAsBytes(message);

        channel.basicPublish(exchange, routingKey, true, properties, body);

        // Wait for confirm (blocking)
        return channel.waitForConfirms(5000);
    }

    @Override
    public void close() throws Exception {
        channel.close();
        connection.close();
    }
}

← Back to the chapter · Previous detail · Next detail →