本文共 3590 字,大约阅读时间需要 11 分钟。
RabbitMQ是一款开源的消息中间件,基于AMQP协议实现,广泛应用于系统间消息传递的解耦。与Kafka、RocketMQ等工具不同,RabbitMQ在实时性要求不高或并发需求较高的场景中表现优异。以下是RabbitMQ的核心概念:
#和*)。RabbitMQ支持消息持久化,以确保消息安全存储:
durable="true"。durable="true"。delivery_mode="PERSISTENT"。在项目依赖中添加RabbitMQ相关组件:
org.springframework.boot spring-boot-starter-amqp org.springframework.boot spring-boot-starter-test
在application.properties中配置RabbitMQ参数:
spring.application.name=rabbitmq-hellospring.rabbitmq.host=localhostspring.rabbitmq.port=5672spring.rabbitmq.username=guestspring.rabbitmq.password=guest
@Componentpublic class Sender { @Autowired private AmqpTemplate rabbitmqTemplate; public void send() { String content = "hello" + new Date(); System.out.println("Sender: " + content); rabbitmqTemplate.convertAndSend("hello", content); }} @Component@RabbitListener(queues = "hello")public class Receiver { @RabbitHandler public void process(String hello) { System.out.println("Receiver: " + hello); }} @Configurationpublic class RabbitConfig { @Bean public Queue helloQueue() { return new Queue("hello"); }} @SpringBootApplicationpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = Application.class)public class HelloApplicationTests { @Autowired private Sender sender; @Test public void hello() { sender.send(); }} @Beanpublic Queue queueMessage() { return new Queue("topic.message");}@Beanpublic Queue queueMessages() { return new Queue("topic.messages");}@Beanpublic TopicExchange exchange() { return new TopicExchange("exchange");}@BeanBinding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange) { return BindingBuilder.bind(queueMessage).to(exchange).with("topic.message");}@BeanBinding bindingExchangeMessages(Queue queueMessages, TopicExchange exchange) { return BindingBuilder.bind(queueMessages).to(exchange).with("topic.#");}public void send() { String content = "hello" + new Date(); rabbitmqTemplate.convertAndSend("exchange", "topic.message", "topic_message"); rabbitmqTemplate.convertAndSend("exchange", "topic.messages", "topic_messages");} @Component@RabbitListener(queues = "topic_message")public class Receiver1 { @RabbitHandler public void process(String hello) { System.out.println("Receiver1: " + hello); }}@Component@RabbitListener(queues = "topic_messages")public class Receiver2 { @RabbitHandler public void process(String hello) { System.out.println("Receiver2: " + hello); }} @BeanBinding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange) { return BindingBuilder.bind(queueMessage).to(exchange);}public void send() { String content = "hello" + new Date(); rabbitmqTemplate.convertAndSend("exchange");} 通过以上配置,可以灵活地实现消息路由策略,充分发挥RabbitMQ的优势。
转载地址:http://rovfk.baihongyu.com/