一 思路总结
1 主要用spring-boot-starter-amqp来整合RabbitMQ和SpringBoot
2 使用spring-boot-starter-test来进行单元测试
3编写配置文件application.yml
spring:
application:
name: rabbitmq-hello
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
4 编写主类Application.class
5 编写Sender并自动扫面,以备自动注入
@Component
public class Sender {
@Autowired
private AmqpTemplate amqpTemplate; public void send() throws Exception {
String context = "hello" + new Date();
System.out.println("Sender:"+context);
this.amqpTemplate.convertAndSend("hello",context);
}
}
6 编写Reveiver并自动扫面同时监听队列hello,并用RabbitHandler来处理请求。
@Component
@RabbitListener(queues = "hello")
public class Receiver { @RabbitHandler
public void process(String hello){
System.out.println("Receiver:"+hello);
}
}
7 编写刚刚用到的hello队列的配置类
@Configuration
public class RabbitConfig {
@Bean
public Queue helloQueue() {
return new Queue("hello");
}
}
8 编写单元测试类Test,调用Sender的方法发送message,这样Receiver就能自动监听并在主类哪里输出了
@SpringBootTest(classes = Application.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class Test { @Autowired
private Sender sender; @org.junit.Test
public void hello() throws Exception {
sender.send();
}
}
9 结果