RabbitMQ的简单实践----->基本消息模型

温馨提示:

以下需要控制台声明队列跟交换机的操作也可用代码实现,具体实现方式见以下文章:

RabbitMQ----代码声明队列及交换机(注解方式)-CSDN博客

简单需求:

  1. 利用RabbitMQ控制台创建队列simple.queue
  2. 在publisher服务中,利用SpringAMQP直接向simple.queue发送消息 (发送服务)
  3. 在consumer服务中,利用SpringAMQP编写消费者,监听simple.queue队列(消费服务)

实践过程:生产者直接发送消息到队列,消费者直接从队列消费

一、控制台创建队列

二、代码实现

1、引入spring-amqp依赖

<!--AMQP依赖,包含RabbitMQ-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2、配置RabbitMQ服务端信息

spring:
  rabbitmq:
    host: localhost  #主机名
    port: 5672   #端口
    virtual-host: /  #虚拟主机
    username: guest  #用户名
    password: guest  #密码

注意:

1、注意这里的端口号是5672端口是AMQP协议的默认端口,用于与RabbitMQ建立非加密连接,所有这里写的是5672,而不是RabbitMQ控制台的默认端口15672。

2、如果是非Linux系统安装的RabbitMQ(我这里是使用Windows),在Windows环境下练习测试,尽量别使用其他新建的用户、队列,使用guest用户就好,因为该用户是默认使用localhost主机名的,其他用户会导致一些不必要的报错。

3、发送消息

使用SpringAMQP提供的RabbitTemplate工具类

import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class SpringAmqpTest {
   @Autowired
    private RabbitTemplate rabbitTemplate;

   @Test
   void testSendMessage2Queue(){
       String queueName = "simple.queue";
       String msg = "hello, amqp!";
       rabbitTemplate.convertAndSend(queueName,msg);
   }
}

4、接收消息


        SpringAMQP提供声明式的消息监听,我们只需要通过注解在方法上声明要监听的队列名称,将来SpringAMQP就会把消息传递给当前方法:

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class MqListener {

    @RabbitListener(queues = "simple.queue")  //监听的队列:simple.queue
    public void listenSimpleQueueMessage(String msg){
        System.out.println("消费者收到消息:【"+msg+"】");
    }
}

总结

springAMQP收发消息过程:

  1. 引入spring-boot-starter-amqp依赖
  2. 配置rabbitmg服务端信息
  3. 利用RabbitTemplate发送消息
  4. 利用@RabbitListener注解声明要监听的队列,监听消息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值