在pom檔案中導入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
在application.properties中添加如下配置資訊
spring.rabbitmq.host=192.168.43.127(這裡配置自己的虛機位址)
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin
建立隊列
package com.etoak.crazy.config.rabbitmq;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
@Bean
public Queue queue() {
//建立隊列名為TEST的隊列
return new Queue("TEST");
}
}
建立生産者
package com.etoak.crazy.study.rabbitmq.producer;
import java.util.Date;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ProducerDemo {
@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
String message = "hello!Now the time is " + new Date();
System.out.println("發送的資訊為 : " + message);
//發送message給名為TEST的隊列
this.rabbitTemplate.convertAndSend("TEST", message);
}
}
建立消費者
package com.etoak.crazy.study.rabbitmq.consumer;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
//監聽名為TEST的隊列
@RabbitListener(queues = "TEST")
public class ConsumerDemo {
//@RabbitListener 标注在類上面表示當有收到消息的時候,就交給 @RabbitHandler 的方法處理,具體使用哪個方法處理
@RabbitHandler
public void process(String message) {
System.out.println("接收消息為 : " + message);
}
}
測試類測試
package com.etoak.crazy.test.rabbitmq;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.etoak.crazy.study.rabbitmq.producer.ProducerDemo;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitmqDemoTest {
@Autowired
private ProducerDemo producerdemo;
@Test
public void hello() throws Exception {
producerdemo.send();
}
}
在虛拟機中service rabbitmq-server start輸入開啟RabbitMQ服務
啟動後輸入service rabbitmq-server status檢視RabbitMQ服務狀态

測試結果: