1、Mac系统rabbitmq消息的简单发送与消费

2020-04-27  本文已影响0人  lois想当大佬

一、基础概念
1、AMQP是Advanced Message Queuing Protocol的简称,它是一个面向消息中间件的开放式标准应用层协议。AMQP定义了这些特性:
消息方向
消息队列
消息路由(包括:点到点和发布-订阅模式)
可靠性
安全性

2、RabbitMQ
RabbitMQ就是以AMQP协议实现的一种中间件产品。

二、安装rabbitmq
https://www.jianshu.com/p/860a9a675fe6

三、启动mq
MAC系统,mq安装目录:/usr/local/Cellar/rabbitmq/xxx
启动:

cd /usr/local/Cellar/rabbitmq/3.8.1
sudo sbin/rabbitmq-server 

mq自带了web客户端:http://localhost:15672 默认账号密码guest/guest

image.png

可以自己点开看看里面都有哪些内容。

四、创建一个springboot项目
springboot已经通过AMQP模块很好的支持了RabbitMQ,我们直接引入starter即可方便使用。
maven的pom.xml文件引入amqp:

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

在application.properties文件中加入rabbitmq的配置:

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=xxx
spring.rabbitmq.password=xxx

创建一个队列:

@Configuration
public class RabbitConfig {
    @Bean
    public Queue helloQueue() {
        return new Queue("lois");
    }
}

创建一个消息发送者:

@Component
public class Sender {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send() {
        String context = "hello world " + new Date();
        System.out.println("Sender : " + context);
        // 把context内容发送到队列lois中
        this.rabbitTemplate.convertAndSend("lois", context);
    }
}

创建一个消息消费者:

@Component
@RabbitListener(queues = "lois")
public class Receiver {
    @RabbitHandler
    public void process(String context) {
        System.out.println("Receiver : " + context);
    }
}

创建测试类

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class ApplicationTests {
    @Autowired
    private Sender sender;
    @Test
    public void hello() throws Exception {
        sender.send();
    }
}

启动项目,控制台输出:

Created new connection: SimpleConnection@73afd117 [delegate=amqp://lois@127.0.0.1:5672/]

运行测试类,控制台输出:

Sender : hello world Mon Apr 27 16:36:07 CST 2020

切换到应用主类的控制台:

Receiver : hello world Mon Apr 27 16:36:07 CST 2020

如果同一个队列拥有多个消费者,情况是怎样的呢?

我们再增加一个消费者:

@Component
@RabbitListener(queues = "lois")
public class Receiver2 {
    @RabbitHandler
    public void process(String context) {
        System.out.println("Receiver2 : " + context);
    }
}

修改测试类:

    @Test
    public void hello() throws Exception {
        sender.send();
        Thread.sleep(1000);
        sender.send();
    }

重新运行应用主类,控制台:同上。

运行测试类,控制台:

Sender : hello world Mon Apr 27 16:42:17 CST 2020
Sender : hello world Mon Apr 27 16:42:18 CST 2020

切换到应用主类,控制台:

Receiver : hello world Mon Apr 27 16:42:17 CST 2020
Receiver2 : hello world Mon Apr 27 16:42:18 CST 2020

总结:
如果多个消费者监听同一个队列,默认情况下,消息会以轮询方式依次发送给各个消费者。

END
如果错漏,望指出!!!

参考资料:
http://blog.didispace.com/

上一篇 下一篇

猜你喜欢

热点阅读