server:
port: 8021
spring:
#给项目来个名字
application:
name: rabbitmq-test
#配置rabbitMq 服务器
rabbitmq:
host: 127.0.0.1
port: 5672
username: need
password: 123456
#虚拟host 可以不设置,使用server默认host
virtual-host: /testhost
2 交换机,队列,绑定等 配置类,核心两个方法拉到最后,其他方法就是正常的创建交换机,队列,绑定等,另外RabbitAdmin 加了@Lazy,解决循环依赖
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import java.util.HashMap;
@Configuration
public class ExchangeQueueBindingConfig {
//自动创建就是靠他
//开启懒加载,不然会有循环依赖问题
@Lazy
@Autowired
RabbitAdmin rabbitAdmin;
//死信队列
@Bean
public Queue createShiXinQueue() {
return new Queue("shixin_queue", true);
}
//死信交换机
@Bean
public DirectExchange createShiXinExchange() {
return new DirectExchange("shixin_exchange", true, false);
}
//死信交换机 死信队列 绑定
@Bean
public Binding createShiXinBinding() {
return BindingBuilder.bind(createShiXinQueue()).to(createShiXinExchange()).with("shixin");
}
//正常队列
@Bean
public Queue createZhengChangQueue() {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("x-dead-letter-exchange", "shixin_exchange");
map.put("x-dead-letter-routing-key", "shixin");
return new Queue("zhengchang_queue", true, false, false, map);
}
//正常交换机
@Bean
public TopicExchange createZhengChangExchange() {
return new TopicExchange("zhengchang_exchange", true, false);
}
//正常交换机 正常队列 绑定
@Bean
public Binding createZhengChangBinding() {
return BindingBuilder.bind(createZhengChangQueue()).to(createZhengChangExchange()).with("chongqing.#");
}
//创建初始化RabbitAdmin对象
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
// 只有设置为 true,spring 才会加载 RabbitAdmin 这个类
rabbitAdmin.setAutoStartup(true);
return rabbitAdmin;
}
//创建交换机和对列
@Bean
public void createExchangeQueue() {
//死信
rabbitAdmin.declareExchange(createShiXinExchange());
rabbitAdmin.declareQueue(createShiXinQueue());
//正常
rabbitAdmin.declareExchange(createZhengChangExchange());
rabbitAdmin.declareQueue(createZhengChangQueue());
}
}