使用RxJava限制来自RabbitMQ的消息

时间:2014-08-18 14:26:54

标签: scala rabbitmq rx-java

我正在使用RxJava从RabbitMQ中提取值。这是代码:

val amqp = new RabbitQueue("queueName")
val obs = Observable[String](subscr => while (true) subscr onNext amqp.next)
obs subscribe (
  s => println(s"String from rabbitmq: $s"), 
  error => amqp.connection.close
)

它工作正常,但现在我要求每秒最多拉一次值,同时保留所有值(因此debounce不会这样做,因为它会丢弃中间值)。

应该像amqp.next blocks thread so we're waiting... (RabbitMQ got two messages in queue) pulled a 1st message... wait 1 second... pulled a 2nd message... wait indefinitely for the next message...

如何使用rx方法实现此目的?

2 个答案:

答案 0 :(得分:2)

一种选择可能是将Schedulers APIPublishSubject结合使用作为可观察对象。

不幸的是,我不知道Scala语法,但这里是您应该能够转换的Java版本:

RabbitQueue amqp = new RabbitQueue("queueName");
Scheduler.Worker worker = Schedulers.newThread().createWorker();
PublishSubject<String> obs = PublishSubject.create();
worker.schedulePeriodically(new Action0() {
    @Override
    public void call() {
        obs.onNext(amqp.next);
    }
}, 1, 1, TimeUnit.SECONDS);

您上面的订阅代码将保持不变:

obs subscribe (
  s => println(s"String from rabbitmq: $s"), 
  error => amqp.connection.close
)

答案 1 :(得分:2)

或者你可以从这样的计时器创建一个observable。我个人认为这更优雅。

RabbitQueue amqp = new RabbitQueue("queueName");
Observable.timer(0, 1, TimeUnit.SECONDS)
        .map(tick -> amp.next())
        .subscribe(...)