SpringBoot 整合 RabbitMQ
生产者
application.yml
# 配置 RabbitMQ 的基本信息
spring:
rabbitmq:
# ip
host: 192.168.36.100
# username
username: ljt
# password
password: ljt
# 端口
port: 5672
virtual-host: /ljt
RabbitMQConfig
package com.www.mq.config;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Www
* @version 1.8
* @since 2023/2/17 12:55 星期五
*/
@Configuration
public class RabbitMQConfig {
/**
* 交换机
*/
public static final String EXCHANGE_NAME = "boot_topic_exchange";
/**
* 队列
*/
public static final String QUEUE_NAME = "boot_queue";
/**
* 1、创建交换机
*
* @return
*/
@Bean("bootExchange")
public Exchange bootExchange() {
return ExchangeBuilder
.topicExchange(EXCHANGE_NAME)
.durable(true)
.build();
}
/**
* 2、创建队列
*
* @return
*/
@Bean("bootQueue")
public Queue bootQueue() {
return QueueBuilder
.durable(QUEUE_NAME)
.build();
}
/**
* 队列和交互机绑定关系 Binding
* <p>
* 1. 知道哪个队列
* <p>
* 2. 知道哪个交换机
* <p>
* 3. routing key
*
* @param queue
* @param exchange
* @return
*/
@Bean
public Binding bindQueueExchange(
@Qualifier("bootQueue") Queue queue,
@Qualifier("bootExchange") Exchange exchange
) {
return BindingBuilder.bind(queue)
.to(exchange)
.with("boot.#")
.noargs();
}
}
ProducerApplicationTests
package com.www.mq;
import com.www.mq.config.RabbitMQConfig;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@SpringBootTest
@RunWith(SpringRunner.class)
class ProducerApplicationTests {
@Resource
private RabbitTemplate rabbitTemplate;
/**
* 发送消息
*/
@Test
void testSend() {
rabbitTemplate.convertAndSend(
RabbitMQConfig.EXCHANGE_NAME,
"boot.wl",
"boot mq hello ...... mq"
);
}
}
消费者
application.yml
# 配置 RabbitMQ 的基本信息
spring:
rabbitmq:
# ip
host: 192.168.36.100
# username
username: ljt
# password
password: ljt
# 端口
port: 5672
virtual-host: /ljt
RabbitMQListener
package com.www.mq.listener;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* @author Www
* @version 1.8
* @since 2023/2/17 13:19 星期五
*/
@Component
public class RabbitMQListener {
/**
* 监听队列
*
* @param message
*/
@RabbitListener(queues = "boot_queue")
public void ListenerQueue(Message message) {
System.out.println("message = " + new String(message.getBody()));
}
}
启动 springboot 项目测试
标签:return,SpringBoot,boot,springframework,RabbitMQ,整合,org,import,public From: https://www.cnblogs.com/wwwljt/p/17129869.html