项目结构 编写yml文件org.springframework.boot spring-boot-starter-amqp
spring:
rabbitmq:
# 地址
host: 172.20.10.7
# 服务器端口
port: 5672
# 账号
username: guest
# 密码
password: llh123456
# SSL
virtual-host: /
编写配置类
package com.guigu.www.springboot_rabbitmq.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
@Bean
public Queue createQueue(){
return new Queue("topics_springBoot");
}
@Bean
public TopicExchange createTopicExchange(){
return new TopicExchange("topics_springBoot_exchange");
}
@Bean
public Binding binding(){
return BindingBuilder.bind(createQueue()).to(createTopicExchange()).with("operation.#");
}
}
编写接收者
package com.guigu.www.springboot_rabbitmq.consumer;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class TopicsConsumer {
@RabbitListener(queues = "topics_springBoot")
public void ConsumerMassges(Object obj){
System.out.println(obj);
}
}
启动SpringBootRabbitmqApplication
测试发布者package com.guigu.www.springboot_rabbitmq;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
@SpringBootTest
class SpringBootRabbitmqApplicationTests {
@Resource
private RabbitTemplate rabbitTemplate;
@Test
void contextLoads() {
rabbitTemplate.convertAndSend("topics_springBoot_exchange","operation.delete","删除成功!!!");
}
}
运行结果:
接收类:
org.springframework.amqp.core.Message
接受消息:
(Body:'删除成功!!!' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=topics_springBoot_exchange, receivedRoutingKey=operation.delete, deliveryTag=1, consumerTag=amq.ctag-krNfa2dtQnyYFgJLZcmR-g, consumerQueue=topics_springBoot])
附上工程链接,仅供学习参考!!!
springBoot_rabbitmq.zip - 蓝奏云文件大小:94.4 K|https://llh317.lanzout.com/i7Lnfy9aibc



