gpt4 book ai didi

java - spring rabbitmq发送动态绑定(bind)交换

转载 作者:搜寻专家 更新时间:2023-11-01 02:05:31 27 4
gpt4 key购买 nike

我尝试使用 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;
}

当我使用发送时(包括 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 - Publishing message on exchange [sample.exchange],routingKey = [qq]怎么了???谢谢

最佳答案

这...

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

...除了创建 Binding 什么都不做对象,然后将其丢弃。你需要拿那个Binding反对并调用 declareBinding在管理员上。您还需要声明交换。

因为您在上下文中有一个管理员;最简单的方法是添加 <rabbit:exchange/>到上下文(连同绑定(bind))。参见 the documentation .

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

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

顺便说一句,主题交换旨在通过关键模式进行路由;如果您只是想使用固定键进行路由/绑定(bind),例如 qq然后使用直接交换。查看RabbitMQ Tutorials .

关于java - spring rabbitmq发送动态绑定(bind)交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35336956/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com