编程语言
首页 > 编程语言> > java – Spring rabbitmq用动态绑定发送到交换

java – Spring rabbitmq用动态绑定发送到交换

作者:互联网

我尝试使用TopicExchange来屏蔽消息.

配置:

    <rabbit:connection-factory id="connectionFactory"  host="localhost" username="guest" password="guest"/>

<rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>

<rabbit:queue name="sample.queue"/>

<rabbit:admin id="rabbitAdmin" connection-factory="connectionFactory" />

<bean id="rabbitListenerContainerFactory"
      class="org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory">
    <property name="connectionFactory" ref="connectionFactory"/>
</bean>

<rabbit:annotation-driven container-factory="rabbitListenerContainerFactory"/>

<rabbit:listener-container connection-factory="connectionFactory" />

零件:

@Component
public class JmsComponent {

    private final Logger log = LoggerFactory.getLogger(JmsComponent.class);

    private final TopicExchange exchange = new TopicExchange("sample.exchange");

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private Queue queue;

    private String received;

    public void send(String msg) {
        rabbitTemplate.convertAndSend("sample.queue", new SimpleMessage(msg));
    }

    public void bindToKey(String keyMask) {
        BindingBuilder.bind(queue).to(exchange).with(keyMask);
        rabbitTemplate.setExchange(exchange.getName());
    }


    public void sendByKey(String key, String msg) {
        rabbitTemplate.convertAndSend(exchange.getName(), key, new SimpleMessage(msg));
    }

    @RabbitListener(queues = "sample.queue")
    public void handle(SimpleMessage message) {
        log.info("================ Received  " + message.getMsg());
        received = message.getMsg();
    }

    public String getReceived() {
        return received;
    }

当我使用send(包括TopicExchange之前) – 一切正常.消息直接发送到队列,handle()已收到它.
但对于TopicExchange ….我尝试使用它:

@Test
public void bind() throws InterruptedException {
    jmsComponent.bindToKey("qq");
    jmsComponent.sendByKey("qq", "message");
    Thread.sleep(5000);
    Assert.isTrue("message".equals(jmsComponent.getReceived()));
}

测试总是失败但是在日志中我看到了这个 – DEBUG o.s.amqp.rabbit.core.RabbitTemplate – 在交换上发布消息[sample.exchange],routingKey = [qq]
怎么了???
谢谢

解决方法:

这个…

BindingBuilder.bind(queue).to(exchange).with(keyMask);

…除了创建一个Binding对象然后扔掉它之外什么都不做.您需要获取该Binding对象并在admin上调用declareBinding.您还需要申报交换.

由于您的上下文中有管理员;最简单的方法是添加< rabbit:exchange />上下文(连同绑定).见the documentation.

<rabbit:queue id="myQueue" name="sample.queue"/>

<topic-exchange name="sample.exchange">
    <bindings>
        <binding queue="myQueue" pattern="bucket.#"/>
    </bindings>
</topic-exchange>

顺便说一句,主题交换用于按关键模式进行路由;如果您只想使用固定密钥路由/绑定,如qq,则使用直接交换.见RabbitMQ Tutorials.

标签:java,spring,rabbitmq,spring-rabbit,rabbitmq-exchange
来源: https://codeday.me/bug/20190528/1167708.html