学习笔记:rabbitmq使用

本文详细介绍如何在Spring Boot项目中整合RabbitMQ,包括配置、创建交换机、队列和绑定,以及发送和接收消息的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导包:

     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

配置:

#rabbitmq配置
spring.rabbitmq.host=10.0.0.19
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/

创建exchange,queue,binding

  • 访问rabbitmq服务:http://10.0.0.1:5672,配置exchange和queue,绑定

  • 使用代码创建,绑定
        @Test
        public void createOrDelete() {
            amqpAdmin.declareExchange(new DirectExchange("amqpadmin.direct.exchange"));
            amqpAdmin.declareQueue(new Queue("amqpadmin.direct.queue"));
            amqpAdmin.declareBinding(
                    new Binding("amqpadmin.direct.queue"
                    , Binding.DestinationType.QUEUE
                    , "amqpadmin.direct.exchange"
                    , "whu.cn"
                    , null));
    
        }
    

     

使用:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootLearnApplicationTests {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    @Test
    public void sendMsgDirect() {
        Map<String, String> map = new HashMap<>();
        map.put("code", "123");
        map.put("msg", "第一条消息");
        map.put("data", "远看一条狗");
        rabbitTemplate.convertAndSend("direct-exchange", "whu.com", map);
    }

    @Test
    public void receiveMsgDirect() {
        Object o = rabbitTemplate.receiveAndConvert("whu.com");
        System.out.println(o);
    }

    @Test
    public void sendMsgTopic() {
        Map<String, String> map = new HashMap<>();
        map.put("code", "123");
        map.put("msg", "第一条消息");
        map.put("data", "远看一条狗");
        rabbitTemplate.convertAndSend("topic-exchange", "th.cn", map);
    }

    @Test
    public void receiveTopic() {
        Object o = rabbitTemplate.receiveAndConvert("th.com");
        System.out.println(o);
    }
}

原理:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值