一 思路總結
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 結果