@Configuration
@PropertySource(value = "classpath:application.properties")
public class RabbitMqConfig {
@Value("${rabbitmq.host}")
private String host;
@Value("${rabbitmq.port}")
private Integer port;
@Value("${rabbitmq.username}")
private String username;
@Value("${rabbitmq.password}")
private String password;
/**
* 通過 AbstractConnectionFactory 獲取到內部 rabbitConnectionFactory
*
* @return
*/
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setHost(host);
connectionFactory.setPort(port);
connectionFactory.setUsername(username);
connectionFactory.setPassword(password);
/**消息確認*/
connectionFactory.setPublisherConfirms(true);
/**消息回調*/
connectionFactory.setPublisherReturns(true);
/**消費者的ack方式爲手動*/
return connectionFactory;
}
/**
* 定義了 AMQP 基礎管理操作,主要是對各種資源(交換機、隊列、綁定)的申明和刪除操作。
*
* @param connectionFactory
* @return
*/
@Bean
RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
RabbitAdmin admin = new RabbitAdmin(connectionFactory);
//創建隊列和交換機以及綁定
/**
* DIRECT
*
* direct : 通過路由鍵 消息將被投送到對應的隊列(一對一)
*/
admin.declareQueue(new Queue("Direct-Queue"));
//該交換機裏面的三個參數分別爲: 名字,持久化,是否自動刪除
admin.declareExchange(new DirectExchange("Joe-Direct", false, false));
Binding direct = BindingBuilder.bind(new Queue("Direct-Queue"))
.to(new DirectExchange("Joe-Direct", true, false)).with("Direct-RoutingKey");
admin.declareBinding(direct);
/**
* FANOUT
*
* 發佈訂閱模式(不存在路由鍵 將被投放到exchange對應的隊列中)
*/
admin.declareQueue(new Queue("Fanout-Queue-1"));
admin.declareQueue(new Queue("Fanout-Queue-2"));
admin.declareQueue(new Queue("Fanout-Queue-3"));
admin.declareExchange(new FanoutExchange("Joe-Fanout", false, false));
Binding fanout1 = BindingBuilder.bind(new Queue("Fanout-Queue-1"))
.to(new FanoutExchange("Joe-Fanout", false, false));
Binding fanout2 = BindingBuilder.bind(new Queue("Fanout-Queue-2"))
.to(new FanoutExchange("Joe-Fanout", false, false));
Binding fanout3 = BindingBuilder.bind(new Queue("Fanout-Queue-3"))
.to(new FanoutExchange("Joe-Fanout", false, false));
admin.declareBinding(fanout1);
admin.declareBinding(fanout2);
admin.declareBinding(fanout3);
/**
* Topic
*
* 可以使得不同源頭的數據投放到一個隊列中(order.log , order.id, purchase.log, purchase.id)
*
* 通過路由鍵的命名分類來進行篩選
*/
admin.declareQueue(new Queue("Topic-Queue-1"));
admin.declareQueue(new Queue("Topic-Queue-2"));
admin.declareQueue(new Queue("Topic-Queue-3"));
admin.declareExchange(new TopicExchange("Joe-Topic", false, false));
Binding topic1 = BindingBuilder.bind(new Queue("Topic-Queue-1"))
.to(new TopicExchange("Joe-Topic", false, false)).with("*.to");
Binding topic2 = BindingBuilder.bind(new Queue("Topic-Queue-2"))
.to(new TopicExchange("Joe-Topic", false, false)).with("log.*");
Binding topic3 = BindingBuilder.bind(new Queue("Topic-Queue-3"))
.to(new TopicExchange("Joe-Topic", false, false)).with("log1.to");
admin.declareBinding(topic1);
admin.declareBinding(topic2);
admin.declareBinding(topic3);
return admin;
}
}