1、目标
通过通配符的方式进行消费的传递与消费
2、实现步骤
- 创建生产者工程:rabbitmq-direct-producer
- 创建消费者工程:rabbitmq-direct-consumer
- 引入spring-boot-rabbitmq的依赖
- 进行消息的分发和测试
- 查看和观察web控制台的状况
3、具体实现
创建生产者工程
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
application.yml配置
server:
port: 8081
spring:
rabbitmq:
host: 110.14.108.10
username: admin
password: admin
port: 5672
virtual-host: /
OrderService
@Service
public class OrderService {
@Autowired
private RabbitTemplate rabbitTemplate;
public void send(String msg){
rabbitTemplate.convertAndSend("topic_exchange","a.email.sms",msg);
}
}
测试类
@SpringBootTest
class RabbitmqTopicProducerApplicationTests {
@Autowired
private OrderService orderService;
@Test
void contextLoads() {
orderService.send("测试内容");
}
}
创建消费者工程
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
application.yml配置
server:
port: 8082
spring:
rabbitmq:
host: 110.14.108.10
username: admin
password: admin
port: 5672
virtual-host: /
Config
@Configuration
public class Config {
// 定义交换机
@Bean
public TopicExchange topicExchange(){
return new TopicExchange("topic_exchange",true,false);
}
// 定义消息队列 true 是否持久化
@Bean
public Queue emailQueue(){
return new Queue("email.topic.queue",true);
}
@Bean
public Queue smsQueue(){
return new Queue("sms.topic.queue",true);
}
// 绑定消息队列、交换机,配置通配符
@Bean
public Binding emailBind(){
return BindingBuilder.bind(emailQueue()).to(topicExchange()).with("*.email.*");
}
@Bean
public Binding smsBind(){
return BindingBuilder.bind(smsQueue()).to(topicExchange()).with("#.sms");
}
}
EmailService
@Service
@RabbitListener(queues = "email.topic.queue")
public class EmailService {
@RabbitHandler
public void email(String msg){
System.out.println("email recive------------>"+msg);
}
}
SmsService
@Service
@RabbitListener(queues = "sms.topic.queue")
public class SmsService {
@RabbitHandler
public void sms(String msg){
System.out.println("sms recive----------->"+msg);
}
}
启动消费者工程
启动测试类contextLoads()
通配符的定义可自行百度,这边不细讲