@Component
public class Sender {
@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
String context = “hello” + new Date();
System.out.printf("Sender: " + context);
this.rabbitTemplate.convertAndSend(“hello”, context);
}
}
创建消息消费者Receiver。通过@RabbitListener注解定义该类对 hello 队列的监听,并用@RabbitHandler 注解来指定对消息的处理方法。所以,该消费者实现了对hello队列的消费,消费操作为输出消息的字符串内容。
@Component
@RabbitListener(queues = “hello”)
public class Receiver {
@RabbitHandler
public void process(String hello) {
System.out.printf("Receiver: " + hello);
}
}
创建RabbitMQ的配置类RabbitConfig,用来配置队列、交换器、路由等高级信息。这里我们以入门为主,先以最小化的配置来定义,以完成一个基本的生产和消费过程。
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitConfig {
@Bean
public Queue helloQueue() {
return new Queue(“hello”);
}
}
接下来我们通过单元测试进行测试
import com.cloud.rabbitmqhello.component.Sender;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class RabbitmqHelloApplicationTests {
@Autowired
private Sender sender;
@Test
void hello() {
sender.send();
}
}
运行结果如下: