您的位置:首页 > 产品设计 > UI/UE

RabbitMQ-AmqpAdmin简单封装以快速创建Queue和Exchange并绑定

2020-06-28 05:08 1476 查看

用以快速创建消息队列(Queue)和交换器(Exchange)并绑定

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RabbitMQCustomizer {

@Autowired
AmqpAdmin amqpAdmin;

private CustomExchange customExchange;
private Queue queue;
private Binding binding;

public void registerExchangeAndQueueAndBinding(String queueName, String routingKey, String exchangeName, String exchangeType) {
this.setCustomExchange(new CustomExchange(exchangeName,exchangeType,true,true));
this.setQueue(new Queue(queueName,true));
this.setBinding(
new Binding(
this.getQueue().getName(),
Binding.DestinationType.QUEUE,
this.getCustomExchange().getName(),
routingKey,
null
)
);
amqpAdmin.declareExchange(this.getCustomExchange());
amqpAdmin.declareQueue(this.getQueue());
amqpAdmin.declareBinding(this.getBinding());
}

private CustomExchange getCustomExchange() {
return customExchange;
}

private void setCustomExchange(CustomExchange customExchange) {
this.customExchange = customExchange;
}

private Queue getQueue() {
return queue;
}

private void setQueue(Queue queue) {
this.queue = queue;
}

private Binding getBinding() {
return binding;
}

private void setBinding(Binding binding) {
this.binding = binding;
}

}

通过调用registerExchangeAndQueueAndBinding方法

传入 (Queue)消息队列名,(routingKey)路由键名,(Exchange)交换器名,(direct、fanout、headers…)交换器类型

示例:

import com.live.config.RabbitMQCustomizer;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class RabbimqApplicationTests {

@Autowired
RabbitMQCustomizer rabbitMQCustomizer;

@Test
void setRabbitMQCustomizer() {
rabbitMQCustomizer
.registerExchangeAndQueueAndBinding(
//消息队列
"direct.queue",
//路由键
"exchange.direct.queue",
//交换器
"exchange.direct",
//交换器类型
ExchangeTypes.DIRECT);
}

}

结果

  • Exchange

  • Queue

  • Binding
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐