import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
public class RabbitConfig {
* 设置Admin, 用于自动创建exchange, queue
* @param connectionFactory
* @return
*/
@Bean
RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
* 这里主要是用于创建Queue, 如果选择手动创建的话,可以省略
* @param rabbitAdmin
* @return
**/
@Bean
Queue queueDispatch(RabbitAdmin rabbitAdmin) {
Queue queue = new Queue("dispatch-event", true);
rabbitAdmin.declareQueue(queue);
return queue;
}
* 这里主要是用于创建exchange topic, 如果选择手动创建的话,可以省略
* @param rabbitAdmin
* @return
**/
@Bean
TopicExchange exchange(RabbitAdmin rabbitAdmin) {
TopicExchange topicExchange = new TopicExchange("dispatch-exchange");
rabbitAdmin.declareExchange(topicExchange);
return topicExchange;
}
* 将queue和具体的exchange关联起来
*/
@Bean
Binding bindingExchangeDispatch(Queue queueDispatch, TopicExchange exchange,RabbitAdmin rabbitAdmin) {
Binding binding = BindingBuilder.bind(queueDispatch).to(exchange).with("dispatch-event");
rabbitAdmin.declareBinding(binding);
return binding;
}
* 配置消息发送MessageConverter
* @param rabbitTemplate
* @return
*/
@Bean
public RabbitMessagingTemplate rabbitMessagingTemplate(RabbitTemplate rabbitTemplate) {
rabbitTemplate.setMessageConverter(new ProtobufMessageConverter());
RabbitMessagingTemplate rabbitMessagingTemplate = new RabbitMessagingTemplate();
rabbitMessagingTemplate.setRabbitTemplate(rabbitTemplate);
return rabbitMessagingTemplate;
}
* 配置接收消息的MessageConverter
* @param connectionFactory
* @return
*/
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setMessageConverter(new ProtobufMessageConverter());
factory.setAcknowledgeMode(AcknowledgeMode.AUTO);
return factory;
}
}