SpringBoot(十三):SpringBoot整合RabbitMQ

本文详细介绍了如何在SpringBoot应用中整合RabbitMQ,包括环境配置、简单队列、工作队列(公平分发和轮询模式)以及订阅和路由模式的实现。通过示例代码展示了如何创建队列、声明消费者、生产消息以及测试不同模式下的消息分发行为。
摘要由CSDN通过智能技术生成

一、环境准备
RabbitMQ 3.7.4
SpringBoot 1.5.10.RELEASE
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
1
2
3
4
application.yml

spring:
  rabbitmq:
    host: 192.168.239.128
    port: 5672
#    username: test
#    password: 123456
#    virtual-host: /vhost_test
#    publisher-confirms: true
1
2
3
4
5
6
7
8
二、简单队列


RabbitMQConfiguration.java 声明队列

package cn.saytime.config;

import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfiguration {

    private static final String QUEUE_SIMPLE_NAME = "test_simple_queue";

    @Bean
    public Queue queue(){
        return new Queue(QUEUE_SIMPLE_NAME, false, false, false, null);
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
消费者

package cn.saytime.listener.simple;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 消费者
 */
@RabbitListener(queues = "test_simple_queue")
@Component
public class SimpleRecv {

    @RabbitHandler
    public void process(String message) {
        System.out.println("[x] rev : " + message);
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
测试生产者

package cn.saytime;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Test
    public void testSimpleQueue() {
        String message = "Hello RabbitMQ !";
        amqpTemplate.convertAndSend("test_simple_queue", message);
        System.out.println("[x] send " + message + " ok");
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
执行test:

[x] send Hello RabbitMQ ! ok
[x] rev : Hello RabbitMQ !
1
2
三、工作队列


However, “Fair dispatch” is the default configuration for spring-amqp

公平分发模式在Spring-amqp中是默认的,这种

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值