【高级应用篇】深入Spring Boot与RabbitMQ:构建可靠的微服务通信
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
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.Configuration;
@Configuration
public class RabbitMQConfig {
private static final String EXCHANGE_NAME = "my-exchange";
private static final String QUEUE_NAME = "my-queue";
private static final String ROUTING_KEY = "my-routing-key";
@Bean
Queue myQueue() {
return new Queue(QUEUE_NAME, true);
}
@Bean
DirectExchange myExchange() {
return new DirectExchange(EXCHANGE_NAME);
}
@Bean
Binding binding(Queue myQueue, DirectExchange myExchange) {
return BindingBuilder.bind(myQueue).to(myExchange).with(ROUTING_KEY);
}
@Bean
RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
}
这段代码定义了一个配置类,它使用Spring AMQP和RabbitMQ的API来创建一个名为my-exchange
的直接交换机,一个名为my-queue
的队列,并将这个队列通过my-routing-key
绑定到这个交换机上。同时,它还提供了一个RabbitAdmin
的Bean,用于管理和自动声明这些RabbitMQ组件。这样,在Spring Boot应用程序启动时,这些组件就会被创建和配置好,可供服务之间的消息通信使用。
评论已关闭