Send and Receive Documents and Images With RabbitMQ in Spring Boot

In this blog post I will cover how to send and receive Documents and Images using RabbitMQ in Spring Boot application.

Previously ( part-i , part-ii, part-iii, part-iv, part-v) I have covered about Sending messages using RabbitMQ in Spring Boot applications. In those examples I have used RabbitMQ to send objects between applications using json format.

Apart from sending objects in JSON format , you could also send images, videos and documents using RabbitMQ.

Let’s first built Direct Exchange and Queues example for our demonstration.

package dev.fullstackcode.sb.rabbitmq.producer.config; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.DirectExchange; import org.springframework.amqp.core.Queue; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; import org.springframework.amqp.support.converter.MessageConverter; import org.springframework.boot.ApplicationRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RabbitMQConfiguration { @Bean Queue queueImages() { return new Queue("queue.images", false); } @Bean Queue queueDocs() { return new Queue("queue.docs", false); } @Bean Queue queueMessages() { return new Queue("queue.messages", false); } @Bean Queue queueJsonMessages() { return new Queue("queue.jsonmessages", false); } @Bean DirectExchange exchange() { return new DirectExchange("exchange.direct"); } @Bean Binding bindingImageQueue(Queue queueImages, DirectExchange exchange) { return BindingBuilder.bind(queueImages).to(exchange).with("event_image"); } @Bean Binding bindingDocQueue(Queue queueDocs, DirectExchange exchange) { return BindingBuilder.bind(queueDocs).to(exchange).with("event_doc"); } @Bean Binding bindingMessageQueue(Queue queueMessages, DirectExchange exchange) { return BindingBuilder.bind(queueMessages).to(exchange).with("event_message"); } @Bean Binding bindingJsonMessageQueue(Queue queueJsonMessages, DirectExchange exchange) { return BindingBuilder.bind(queueJsonMessages).to(exchange).with("event_jsonMessage"); } @Bean ApplicationRunner runner(ConnectionFactory cf) { return args -> cf.createConnection().close(); } @Bean MessageConverter messageConverter() { return new Jackson2JsonMessageConverter(); } @Bean RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) { RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); rabbitTemplate.setMessageConverter(messageConverter()); return rabbitTemplate; } }
Code language: Java (java)

In Spring Boot, RabbitMQ integration, Message class used to transfer information. The purpose of the Message class is to simply encapsulate the body and properties within a single instance. When performing an operation such as Publish the content is passed as a byte-array argument and additional properties are passed in as separate argument

We will see how to use this Message class to send and Receive string, Objects, images and documents.

Sending and Receiving String

Let’s see how to send and receive simple String message

Producer Application can use below code to send simple String.

MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("text/plain"); Message message = new Message(event.getName().getBytes(), messageProperties); rabbitTemplate.send(directExchange.getName(), "event_message", message);
Code language: Java (java)

Content Type – sets type of information being sent in the message. For simple string it is text/plain

Consumer Application can use below code receive message and convert into String

@RabbitListener(queues = "queue.messages") private void receiveQueueC(Message message) { log.info("Event received from queue.messages-> {}", new String(message.getBody(), StandardCharsets.UTF_8)); }
Code language: Java (java)

Output

Event received from queue.messages-> Event A
Code language: Java (java)

Sending and Receiving Object

Let’s see how to send and receive simple Object using Message class.

Producer application

ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(event); MessageProperties messageProperties = new MessageProperties(); //Note that you must change the contentType to application/json messageProperties.setContentType("application/json"); Message message1 = new Message(json.getBytes(), messageProperties); rabbitTemplate.convertAndSend(directExchange.getName(),"event_jsonMessage", message1);
Code language: Java (java)

application/json – content type for json String.

Consumer Application.

@RabbitListener(queues = "queue.jsonmessages") private void receiveQueueJsonMessages(Message message) { ObjectMapper mapper = new ObjectMapper(); Event event; try { event = mapper.readValue(message.getBody(),Event.class); } catch (IOException e) { throw new RuntimeException(e); } log.info("Event received from queue.jsonmessages -> {} , {}", event.getName(), event.getId()); }
Code language: Java (java)

I have used ObjectMapper class to convert json string back to object.

Output

Event received from queue.jsonmessages -> Event B , 2
Code language: Java (java)

Sending and Receiving Image

Producer Application

Resource resource=resourceLoader.getResource("classpath:images/A.png"); byte[] body ; try { File file = resource.getFile(); body = Files.readAllBytes(file.toPath()); } catch (IOException e) { throw new RuntimeException(e); } MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("image/png"); messageProperties.getHeaders().put("extension", "png"); messageProperties.getHeaders().put("name", "A"); Message message = new Message(body, messageProperties); rabbitTemplate.convertAndSend(directExchange.getName(),"event_image", message);
Code language: Java (java)

Note

As we are sending PNG image we are setting content type as image/png. If it is jpg it should be image/jpg. Depending on the type of image, you need set the content type .

Consumer Application

@RabbitListener(queues = "queue.images") private void receiveImages(Message message) { MessageProperties messageProperties = message.getMessageProperties(); String fileName = messageProperties.getHeader("name"); String extension = messageProperties.getHeader("extension"); Path path = Paths.get("E://rabbitmq//"+fileName+"."+extension); try { Files.write(path, message.getBody() ); } catch(IOException e) { log.error("Error writing file (queue.images)-> {}",e); } log.info("Event received from queue.images -> {}",message.toString()); }
Code language: Java (java)

Sending and Receiving Documents

Producer Application

Resource resource=resourceLoader.getResource("classpath:docs/sample.docx"); byte[] body = new byte[0]; try { File file = resource.getFile(); body = Files.readAllBytes(file.toPath()); } catch (IOException e) { throw new RuntimeException(e); } MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); messageProperties.getHeaders().put("extension", "docx"); messageProperties.getHeaders().put("name", "sample"); Message message = new Message(body, messageProperties); rabbitTemplate.convertAndSend(directExchange.getName(),"event_doc", message);
Code language: Java (java)

Consumer Application

@RabbitListener(queues = "queue.docs") private void receiveDocs(Message message) { MessageProperties messageProperties = message.getMessageProperties(); String fileName = messageProperties.getHeader("name"); String extension = messageProperties.getHeader("extension"); Path path = Paths.get("E://rabbitmq//"+fileName+"."+extension); try { Files.write(path, message.getBody() ); } catch(IOException e) { log.error("Error writing file (queue.docs) -> {}",e); } log.info("Event received from queue.docs -> {}",message.toString()); }
Code language: Java (java)

You can download the source code for this blog post from GitHub.

Producer – sureshgadupu/sb-rabbitmq-image-sending (github.com)

Consumer – sureshgadupu/sb-rabbitmq-image-receive (github.com)

Similar Posts