配置类—启动时自动创建mq
@Configuration
@Data
public class RabbitMqQueueConfig {
//Topic类型的交换机
@Bean
public Exchange contractParamsExchange() {
return new TopicExchange(交换机名称, true, false);
}
//dirct类型的交换机
@Bean
public Exchange registerContractEventExchange() {
return new DirectExchange(交换机名称);
}
//创建队列
@Bean
public Queue registerContractEventQueue() {
return new Queue(队列名, true);
}
//绑定队列和交换机
@Bean
public Binding registerLogContractEventBinding() {
return new Binding(队列名称,Binding.DestinationType.QUEUE,交换机名称,路由key,
null);
}
}
在java代码中创建mq相关信息
这里主要使用了AmqpAdmin
//创建交换机 DirectExchange directExchange = new DirectExchange(exchangeName); amqpAdmin.declareExchange(directExchange); //创建队列 Queue queue = new Queue(queueName, true); amqpAdmin.declareQueue(queue); //绑定交换机、队列、路由 Binding binding = BindingBuilder.bind(queue).to(directExchange).with(routingKey); amqpAdmin.declareBinding(binding);
解除绑定和删除交换机、队列
//解除队列绑定 Binding bindingOld = BindingBuilder.bind(new Queue(queueName)).to(new DirectExchange(exchangeName)).with(routingKey); amqpAdmin.removeBinding(bindingOld); //删除队列 amqpAdmin.deleteQueue(queueName); //删除交换机 amqpAdmin.deleteExchange(exchangeName);