Create work(s) queue with SpringBoot and RabbitMQ

Chung Khanh Duy
Jul 4, 2018 · 3 min read
package com.example.spring.rabbitmq.config;

import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import com.example.spring.rabbitmq.service.TaskReceiver;
import com.example.spring.rabbitmq.service.TaskSender;

@Configuration
public class RabbitMQConfiguration {

@Bean
public Queue hello() {
return new Queue("hello");
}

private static class ReceiverConfig {

@Bean
public TaskReceiver receiver() {
return new TaskReceiver();
}

}

}
package com.example.spring.rabbitmq.service;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.util.StopWatch;

@RabbitListener(queues = "hello")
public class TaskReceiver {

@RabbitHandler
public void receive(String in) throws InterruptedException {
StopWatch watch = new StopWatch();
watch.start();
System.out.println(" [x] Received '" + in + "'");
doWork(in);
watch.stop();
System.out.println(" [x] Done in " + watch.getTotalTimeSeconds() + "s");
}

private void doWork(String in) throws InterruptedException {
for (char ch : in.toCharArray()) {
if (ch == '.') {
Thread.sleep(1000);
}
}
}
}
@Service
public class TaskSender {

@Autowired
private RabbitTemplate template;

@Autowired
private Queue queue;

@PostConstruct
public void send() {
try {
for (int i = 0; i < 5; i++) {
String message = "hello" + i;
template.convertAndSend(queue.getName(), message);
System.out.println(" [x] Sent '" + message + "'");
}
} catch (Exception e) {
e.printStackTrace();
}
}

}
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest

Chung Khanh Duy

Written by

Solution Architect@Formos | SW Engineer | Hunsband | A Father | A person who love to build softwares

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade