【RabbitMQ的那点事】与Spring boot集成(主要是Exchange类型的集成,入门)

本文是RabbitMQ与Spring boot集成示例,实现了三种Exchange类型:

  • DefaultExchange
  • FanoutExchange
  • TopicExchange
    (还有一种HeaderExchange,没有写示例)

关于Exchange类型介绍,戳:https://www.jianshu.com/p/d9561f13e28b

文章内容:

Spring boot集成RabbitMQ

1. 环境

1.1 RabbitMQ用的是 3.6.1版本:

MacBook-Pro% brew install rabbitmq
Warning: rabbitmq-3.6.1 already installed

1.2 新建virtual host(不是必须):
为了不受别的vhost影响,特地新建了一个Virtual host。
如果在测试中发现遇到connect refued问题,记得给新建的vhost赋上user权限。

virtual host

1.3 Spring boot用的是2.5.7版本
1.4 test用的是spring-boot-starter-test以及junit-juspier:5.7.2
1.5 引入依赖:

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

1.6 新建yaml:

spring:
  rabbitmq:
    username: guest
    password: guest
    port: 5672
    host: localhost
    virtual-host: spring-boot-test

2. Direct Exchange

  • a. 首先是定义direct queue bean, durable=false,表示当broker重启时,这个queue就会被删除。注:我们application重启并不会影响queue的删除。
  • b. 其次定义一个exchange,类名是DirectExchange,这个类是Spring的org.springframework.amqp.core包里的。
  • c. 绑定是交换器和消息队列之间的关系,告诉交换器如何路有消息。

// 绑定命令的伪代码
Queue.Bind <queue> TO <exchange> WHERE <condition>

在Spring中可以使用BindingBuilder将exchange按routingKey的规则和queue进行绑定。

  • d. 消息的消费端,使用注解@RabbitListener来监听queueName=direct.queue的队列,支持同时监听多个队列。
@Configuration
public class DirectExchangeConfig {
    @Bean
    public Queue directqueue() {
        return new Queue("direct.queue", false);
    }

    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange("direct.exchange");
    }

    @Bean
    public Binding directBinding(Queue directqueue, DirectExchange directExchange) {
        return BindingBuilder.bind(directqueue).to(directExchange).with("direct-routing-key");
    }

    @RabbitListener(queues = "direct.queue")
    public void listen(String in) {
        System.out.println("Direct Message Listener: " + in);
    }
}

消息发送:使用RabbitTemplate进行发送:

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

    @Test
    public void sendMessageToDirectExchange() {
        rabbitTemplate.convertAndSend("direct.exchange", "direct-routing-key", "hello, i am direct message!");
    }
}

3. FanoutExchange

Set fanout exchange,绑定两个queue。利用两个@RabbitListener分别监听这两个queue。
Spring支持使用Declarables对象来一次性的绑定多条:

@Configuration
public class FanoutExchangeConfig {
    @Bean
    public Declarables fanoutBindings() {
        Queue fanoutQueue1 = new Queue("fanout.queue1", true);
        Queue fanoutQueue2 = new Queue("fanout.queue2", true);
        FanoutExchange fanoutExchange = new FanoutExchange("fanout.exchange");

        return new Declarables(
                fanoutQueue1,
                fanoutQueue2,
                fanoutExchange,
                bind(fanoutQueue1).to(fanoutExchange),
                bind(fanoutQueue2).to(fanoutExchange));
    }

    @RabbitListener(queues = {"fanout.queue1"})
    public void receiveMessageFromFanout1(String message) {
        System.out.println("Received fanout 1 message: " + message);
    }

    @RabbitListener(queues = {"fanout.queue2"})
    public void receiveMessageFromFanout2(String message) {
        System.out.println("Received fanout 2 message: " + message);
    }
}

发送消息:

    public void sendMessageToFanoutExchange() {
        rabbitTemplate.convertAndSend("fanout.exchange", "", "hello, i am fanout message!");
    }

fanout模式下,convertAndSend方法将忽略routingKey。即如果在发送的时候set了routingKey=abc,其实在fanout模式下也没有关系,绑定的queue依然能收到消息。

也就是说:在发送的时候把routingKey改成abc也不会影响消息的发送:

    public void sendMessageToFanoutExchange() {
        rabbitTemplate.convertAndSend("fanout.exchange", "abc", "hello, i am fanout message!");
    }

4. Topic Exchange

@RabbitListener支持同时监听多个queue:

@Configuration
public class TopicExchangeConfig {
    @Bean
    public Declarables topicBindings() {
        Queue topicQueue1 = new Queue("topic.queue1", true);
        Queue topicQueue2 = new Queue("topic.queue2", true);

        TopicExchange topicExchange = new TopicExchange("topic.exchange");

        return new Declarables(
                topicQueue1,
                topicQueue2,
                topicExchange,
                BindingBuilder
                        .bind(topicQueue1)
                        .to(topicExchange).with("*.important.*"),
                BindingBuilder
                        .bind(topicQueue1)
                        .to(topicExchange).with("#.error"),
                BindingBuilder
                        .bind(topicQueue2)
                        .to(topicExchange).with("#.error"));
    }


    @RabbitListener(queues = {"topic.queue1", "topic.queue2"})
    public void receiveMessageFromTopic(String message) {
        System.out.println("Received topic message: " + message);
    }
}

发送消息:

    public void sendMessageToTopicExchange() {
        rabbitTemplate.convertAndSend("topic.exchange", "a.important.b", "important message!");
        rabbitTemplate.convertAndSend("topic.exchange", "a.error", "error message!");
    }

run程序后,控制台打印:
Received topic message: important message!
Received topic message: error message!
Received topic message: error message!

按上述配置,使用routingKey=a.important.b发送消息,只有topic.queue1能收到。
使用routingKey=a.error发送消息,topic.queue1和topic.queue2都能收到。
这就是为什么会打印出三条消息的原因。


参考
baeldung - Messaging with Spring AMQP
baeldung - RabbitMQ Message Dispatching with Spring AMQP

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,825评论 4 377
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,887评论 2 308
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,425评论 0 255
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,801评论 0 224
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,252评论 3 299
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,089评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,216评论 2 322
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 31,005评论 0 215
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,747评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,883评论 2 255
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,354评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,694评论 3 265
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,406评论 3 246
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,222评论 0 9
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,996评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,242评论 2 287
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 36,017评论 2 281

推荐阅读更多精彩内容