问题描述
我有一个交换台(exchange1
),可以根据路由键表达式将其路由到n
个不同的队列。
,将来,队列号可以增加((所有视频和mp4扩展名都应加入queue4
)
我们如何动态创建队列并将其绑定到一个特定的交换机,并且应该仅使用一个流侦听器?
解决方法
使用属性无法直接通过Spring Cloud Stream完成。
您将必须使用所需的路由键声明Exchange
,Queue
和Binding
@Bean
,然后将使用者绑定配置为不声明队列和绑定)然后设置s.c.s.consumer.multiplex=true
和s.c.s.destination=queue1,queue2,queue3
。
有关如何禁用活页夹设置的信息,请参见Using Existing Queues/Exhanges。
,使用Spring引导中的Spring-AMQP插件可以轻松完成此操作。我在下面附上了如何实现的摘要。 (我相信代码所讲的不只是理论上的话):
package com.savk.workout.spring.rabbitmqconversendreceivefanoutproducer;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class DynamicBindingDemo {
@Autowired
private RabbitAdmin rabbitAdmin;
@Autowired
private RabbitTemplate rabbitTemplate;
private boolean switchedOn = true;
//Toggle binding programatically
@Scheduled(fixedRate = 10000L)
public void manipulateBinding() {
Exchange exchange = ExchangeBuilder.directExchange("exchange").autoDelete().build();
Queue queue = QueueBuilder.nonDurable("queue").build();
Binding binding = BindingBuilder.bind(queue).to(exchange).with("routingkey").noargs();
if(switchedOn) {
rabbitAdmin.declareBinding(binding);
} else {
rabbitAdmin.removeBinding(binding);
}
}
@Bean
public RabbitAdmin rabbitAdmin() {
return new RabbitAdmin(rabbitTemplate.getConnectionFactory());
}
}
确保您也有相应的RabbitListener:
@RabbitListener(queues = "queuename")
@RabbitHandler
public String handle(String msg) {
System.out.println("RCVD :: " + msg);
String response = "PONG { " + msg + " } from INSTANCE " + INSTANCE;
return response;
}
您看到所有事情都可以动态完成。您所需要做的就是通过绑定进行操作。