1.生產端
1. 創建生產者SpringBoot工程
? 2. 引入start,依賴坐標
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
? 3. 編寫yml配置,基本信息配置
spring:rabbitmq:host:公網ipport:5671username: password:virtual-host:
? 4. 定義交換機,隊列以及綁定關系的Config配置類
@Configuration
public class RabbitMqConfig {//定義交換機的名字public static final String EXCHANGE_NAME = "boot_topic_exchange";//定義隊列的名字public static final String QUEUE_NAME = "boot_queue";//1、聲明交換機@Bean("bootExchange") //bean聲明,加入到容器中public Exchange bootExchange(){//topicExchange: 主題交換機 durable:是否持久化//ExchangeBuilder工具類調用topicExchange的API方法創建主題交換機return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();}//2、聲明隊列@Bean("bootQueue")public Queue bootQueue(){return QueueBuilder.durable(QUEUE_NAME).build();}//3、隊列與交換機進行綁定@Beanpublic Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange){return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();}}
? 5. 注入RabbitTemplate,調用方法,完成消息發送
@SpringBootTest
@RunWith(SpringRunner.class)
public class ProducerTest {//注入 RabbitTemplate@Autowiredprivate RabbitTemplate rabbitTemplate;@Testpublic void send(){rabbitTemplate.convertAndSend("boot_topic_exchange","boot.haha","boot mq...");}
}
2.消費端?
1. 創建消費者SpringBoot工程
? 2. 引入start,依賴坐標
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
? 3. 編寫yml配置,基本信息配置
spring:rabbitmq:host:公網ipport:5671username: password:virtual-host:
? 4. 定義監聽類,使用@RabbitListener注解完成隊列監聽。
@Component //聲明這是一個組件
public class RabbitMQListener {//定義方法進行信息的監聽 RabbitListener中的參數用于表示監聽的是哪一個隊列//如果有消息過來,就會執行這個方法,自動會把消息封裝到Message對象中,取走消息之后會在隊列里刪除掉消息@RabbitListener(queues = "boot_queue")public void ListenerQueue(Message message){System.out.println("message:"+message.getBody());}
}
3.啟動流程
先點擊生產端的@test方法發送信息到隊列中去,然后直接運行消費端的
@SpringBootApplication啟動方法