spring boot 中使用 RabbitMQ 教程二 work queue 使用多个消费者,消费队列中的消息(一对多)

spring boot 中使用 RabbitMQ 教程一 生产者、队列、消费者,中讲的是,一对一的关系。这次我们来探寻一对多的关系。

  • RabbitMQ给我提供了类似一对多的关系,就是多个相同的消费者,来消费同一个队列中的消息。使用多个消费者来消费同一个队列中的消息,使这些消息将会平均分到各个消费者中进行消费。

    一对多

  • 基本的例如启动rabbitmq-server和配置application.properties这里就不谈了。请查看上期内容。

  • 定义一个队列workQueue,两个消费者workReceiver 、workReceiver 1,一个生产者workSend

import com.zb.rabbitMQtest.workqueues.receiver.WorkReceiver;
import com.zb.rabbitMQtest.workqueues.send.WorkSend;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 张博
 */
@Configuration
public class RabbitMQConfig {

    @Bean
    public Queue workQueue() {
        return new Queue("work-queue");
    }

    @Bean
    public WorkReceiver workReceiver() {
        return new WorkReceiver("Receiver0");
    }

    @Bean
    public WorkReceiver workReceiver1() {
        return new WorkReceiver("Receiver1");
    }

    @Bean
    public WorkSend workSend() {
        return new WorkSend();
    }
}
  • 定义消费者类。使用@RabbitListener,监听名字为work-queue的队列,接收到消息后,会把消息循环分发到,之前定义的两个消费者对象上。
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author 张博
 */
@Component
public class WorkReceiver {

    private String receiverInstance;

    public WorkReceiver(String receiverInstance) {
        this.receiverInstance = receiverInstance;
    }

    @RabbitListener(queues = "work-queue")
    public void receive(String str) {
        System.out.println(receiverInstance.concat(" =====: ").concat(str));
    }
}
  • 定义生产者类,使用RabbitTemplate提供的convertAndSend方法一次性发送10条消息到队列中。
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 张博
 */
@Component
public class WorkSend {

    @Autowired
    private Queue workQueue;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send() {
        for (int i = 0; i < 10; i++) {
            String msg = "你好 " + i;
            System.out.println("send =====:".concat(msg));
            rabbitTemplate.convertAndSend(workQueue.getName(), msg);
        }
    }
}
  • 测试
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @author 张博
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class WorkSendTest {

    @Autowired
    private WorkSend workSend;

    @Test
    public void send() throws Exception {
        workSend.send();
    }
}
  • 运行结果,spring-amqp 默认采用的是公平调度(Fair dispatch)的形式。
send =====:你好 0
send =====:你好 1
send =====:你好 2
send =====:你好 3
send =====:你好 4
send =====:你好 5
send =====:你好 6
send =====:你好 7
send =====:你好 8
send =====:你好 9

Receiver1 =====: 你好 1
Receiver0 =====: 你好 0
Receiver0 =====: 你好 2
Receiver1 =====: 你好 3
Receiver0 =====: 你好 4
Receiver1 =====: 你好 5
Receiver0 =====: 你好 6
Receiver1 =====: 你好 7
Receiver0 =====: 你好 8
Receiver1 =====: 你好 9
  • 公平调度或循环调度。
    默认时RabbitMQ将每条发送的消息都将由下一个消费者进行消费,就是说每个消费者都能与其它消费者接收到相同的数量的消息。但是问题来了,假如A消费者接到消息处理时间很长,B消费者接收到的消息处理时间很短,那么B消费者大部分时间将处于空闲状态下。这样时间一长性能会下降,至少看起来没那么均匀了。这种做法就是“循环调度”。RabbitMQ只是当消息进入到队列中时进行消息的分发调度。并没有考虑到消费者具体完成消费的数量。
    而且在spring-amqp默认采用的是公平调度。并不是循环调度,那种只注意分发同等消息数量给消费者的情况。如果想使用循环调度的话,那么设置SimpleMessageListenerContainer中的DEFAULT_PREFETCH_COUNT = 0即可。DEFAULT_PREFETCH_COUNT = 1是公平调度。请看这里
  • 根据上面的例子把公平调度修改成循环调度factory.setPrefetchCount(0);
import com.zb.rabbitMQtest.workqueues.receiver.WorkReceiver;
import com.zb.rabbitMQtest.workqueues.send.WorkSend;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 张博
 */
@Configuration
public class RabbitMQConfig {

    @Bean
    public Queue workQueue() {
        return new Queue("work-queue");
    }

    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory());
        factory.setPrefetchCount(0);
        return factory;
    }

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory cachingConnectionFactory =  new CachingConnectionFactory("127.0.0.1", 5672);
        cachingConnectionFactory.setUsername("guest");
        cachingConnectionFactory.setPassword("guest");
        return cachingConnectionFactory;
    }

    @Bean
    public WorkReceiver workReceiver() {
        return new WorkReceiver("Receiver0");
    }

    @Bean
    public WorkReceiver workReceiver1() {
        return new WorkReceiver("Receiver1");
    }

    @Bean
    public WorkSend workSend() {
        return new WorkSend();
    }
}
  • @RabbitListener添加属性containerFactory创建指定监听此队列上的一个消息监听容器。
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author 张博
 */
@Component
public class WorkReceiver {

    private String receiverInstance;

    public WorkReceiver(String receiverInstance) {
        this.receiverInstance = receiverInstance;
    }

    @RabbitListener(queues = "work-queue", containerFactory = "rabbitListenerContainerFactory")
    public void receive(String str) {
        System.out.println(receiverInstance.concat(" =====: ").concat(str));
    }
}
  • prefetchCount设置为1时表示,你不要给我发新的消息了,等我处理完你再给我发新的消息。这时它会把这个消息交给空闲的消费者进行处理。这样看起来很公平。
    公平调度

导航

spring boot 中使用 RabbitMQ 教程一 生产者、队列、消费者

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

推荐阅读更多精彩内容