环境:jdk11,springboot2.5.5
以下代码以路由模式(Routing)为示例。
1. pom.xml
4.0.0 org.springframework.boot spring-boot-starter-parent2.5.5 com.example spring-rabbitmq-demo0.0.1-SNAPSHOT spring-rabbitmq-demo Demo project for Spring Boot 11 org.springframework.boot spring-boot-starter-amqporg.springframework.boot spring-boot-starter-testtest org.springframework.amqp spring-rabbit-testtest org.springframework.boot spring-boot-maven-plugin
2. application.yml
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: admin
password: 123456
virtual-host: /
3. 配置队列,交换机,以及绑定关系
@Configuration
public class RabbitMQConfiguration {
// 创建队列
@Bean
public Queue orderQueue() {
return new Queue("order-queue", true, false, false, null);
}
@Bean
public Queue courseQueue() {
return new Queue("course-queue", true, false, false, null);
}
// 创建交换机
@Bean
public DirectExchange directExchange() {
// 交换机名称,是否持久化,是否自动删除,附加参数
return new DirectExchange("direct-exchange", true, false, null);
}
// 绑定交换机和队列
@Bean
public Binding bindingDirect1() {
return BindingBuilder.bind(orderQueue()).to(directExchange()).with("order");
}
@Bean
public Binding bindingDirect2() {
return BindingBuilder.bind(courseQueue()).to(directExchange()).with("course");
}
}
4. 配置消费者监听
@Service
public class ConsumerService {
@RabbitListener(queues = "order-queue")
public void orderConsumer(Message message) {
System.out.println("orderConsumer收到消息: " + new String(message.getBody(), StandardCharsets.UTF_8));
}
@RabbitListener(queues = "course-queue")
public void courseConsumer(Message message) {
System.out.println("courseConsumer收到消息: " + new String(message.getBody(), StandardCharsets.UTF_8));
}
}
5. 编写测试用例发送消息
@SpringBootTest
class SpringRabbitmqDemoApplicationTests {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void sendMessage1() {
rabbitTemplate.convertAndSend("direct-exchange","order","hello order");
}
@Test
void sendMessage2() {
rabbitTemplate.convertAndSend("direct-exchange","course","hello course");
}
}
6. SpringBoot启动类,启动项目
@SpringBootApplication
public class SpringRabbitmqDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRabbitmqDemoApplication.class, args);
}
}
7. 运行测试类发送消息,进行测试
完整代码



