原始Rabbit API声明
channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
channel.queueDeclare(queueName, false, false, false, null);
channel.queueBind(queueName, exchangeName, routingKey);
使用SpringAMQP去声明,就需要使用SpringAMQP的如下模式,即声明@Bean方式
package club.yunqiang.rabbitmqspring;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* @author 张云强
* @date 2019/12/9
*/
@Configuration
@ComponentScan({"club.yunqiang.rabbitmqspring"})
public class RammitMQConfig {
@Bean
public ConnectionFactory connectionFactory(){
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setAddresses("localhost:5672");
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
connectionFactory.setVirtualHost("/");
return connectionFactory;
}
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
rabbitAdmin.setAutoStartup(true);
return rabbitAdmin;
}
/**
* 针对消费者配置
* 1、设置交换机类型
* 2、将队列绑定到交换机
* FanoutExchange:将消息分发到所有的绑定队列,无routingKey概念
* HeadersExchange:通过添加属性key-value匹配
* DirectExchange:按照routingKey分发到指定队列
* TopicExchange:多关键字匹配
*/
@Bean
public TopicExchange exchange001(){
return new TopicExchange("topic001", true, false);
}
@Bean
public Queue queue001(){
return new Queue("queue001", true);
}
@Bean
public Binding binding001(){
return BindingBuilder.bind(queue001()).to(exchange001()).with("spring.*");
}
@Bean
public TopicExchange exchange002(){
return new TopicExchange("topic002", true, false);
}
@Bean
public Queue queue02(){
return new Queue("queue002", true);
}
@Bean
public Binding binding002(){
return BindingBuilder.bind(queue02()).to(exchange002()).with("rabbit.*");
}
@Bean
public Queue queue003(){
return new Queue("queue003", true);
}
@Bean
public Binding binding003(){
return BindingBuilder.bind(queue003()).to(exchange001()).with("mq.*");
}
@Bean
public Queue queue_image(){
return new Queue("queue_image", true);
}
@Bean
public Queue queue_pdf(){
return new Queue("queue_pdf", true);
}
}
注意:本文归作者所有,未经作者允许,不得转载