引入依赖jar包
org.springframework.boot
spring-boot-starter-amqp
引入配置
@Configuration
public class RabbitConfig {final static String message = "sanguo.message";
final static String message2 = "sanguo.message2";
final static String TOPIC_EXCHANGE ="exchange";
@Bean
public Queue queue1() {
return new Queue(message);
}@Bean
public Queue queue2() {
return new Queue(message2);
}@Bean
TopicExchange exchange() {
return new TopicExchange(TOPIC_EXCHANGE);
}@Bean
Binding bindingExchangeMessages(Queue queue1, TopicExchange exchange) {
System.out.println(queue1.getName());
return BindingBuilder.bind(queue1).to(exchange).with("sanguo.#");
}@Bean
Binding bindingExchangeMessage(Queue queue2, TopicExchange exchange) {
System.out.println(queue2.getName());
return BindingBuilder.bind(queue2).to(exchange).with("sanguo.message");
}
}
这里做个笔记,RabbitMQ是通过交换机给queue发消息,但是中间还会通过RoutingKey进行过滤,BindingBuilder.bind(queue2).to(exchange).with(“sanguo.message”) 这句话的意思就是,通过交换机exchange发送的消息,满足RoutingKey条件的(sanguo.message)会被转发到queue2里面 下面是具体的消息发送
@Component
public class HelloSender {@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
String context = "hello " + LocalDateTime.now();
System.out.println("Sender : " + context);
this.rabbitTemplate.convertAndSend("exchange","sanguo.aaa", context);
//交换机,key,具体内容
}
}
【SpringBoot整合RabbitMQ 简单示例】接收端–记得也要引入上面的依赖
@Component
@RabbitListener(queues = "sanguo.message")
public class HelloReceiver {
//这里接收类型可以指定一个对象
@RabbitHandler
public void process(String hello) {
System.out.println("Receiver: " + hello);
}}
配置文件(接收端和发送端都需要)
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
推荐阅读
- 第五节:SpringBoot常用注解介绍
- 第四节:SpringBoot中web模版数据渲染展示
- SpringBoot2022【草稿】
- 聊聊springboot项目全局异常处理那些事儿
- 第一节:创建SpringBoot项目并运行HelloWorld
- springboot管理系统[基于员工角色和文件权限的分级的后台管理系统源码]
- SpringBoot之@ComponentScan和@SpringBootApplication扫描覆盖问题
- mybatis|记mybatis查询null字段导致的NPE
- SpringBoot|SpringBoot 整合 druid数据源
- springboot项目配置application添加图片映射 (windows and linux 都可使用)