1、目标
根据不同的路由key,将消息分发到不同的消息队列queue中,并被消费者消费
2、实现步骤
- 创建生产者工程:rabbitmq-direct-producer
- 创建消费者工程:rabbitmq-direct-consumer
- 引入spring-boot-rabbitmq的依赖
- 进行消息的分发和测试5:查看和观察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: 8082
spring:
rabbitmq:
host: 110.14.218.10 //rabbitmq被我安装在远程服务上,这是地址,本地安装的用127.0.0.1
port: 5672
username: admin
password: admin
virtual-host: /
OrderService
@Service
public class OrderService {
@Autowired
private RabbitTemplate rabbitTemplate;
public void send(String msg){
rabbitTemplate.convertAndSend("direct_echange","email",msg);
rabbitTemplate.convertAndSend("direct_echange","sms",msg);
}
}
测试类
@SpringBootTest
class RabbitmqDirectProducerApplicationTests {
@Autowired
private OrderService orderService;
@Test
void contextLoads() {
orderService.send("测试内容11145");
}
}
4、创建消费者工程
依赖
<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
port: 5672
username: admin
password: admin
virtual-host: /
Config
@Configuration
public class Config {
@Bean
public DirectExchange directExchange(){
return new DirectExchange("direct_echange",true,false);
}
@Bean
public Queue emailQueue(){
return new Queue("email.direct.queue",true);
}
@Bean
public Queue sms(){
return new Queue("sms.direct.queue",true);
}
//绑定交换机和消费队列,定义路由
@Bean
public Binding emailBinding(){
return BindingBuilder.bind(emailQueue()).to(directExchange()).with("email");
}
@Bean
public Binding smsBinding(){
return BindingBuilder.bind(sms()).to(directExchange()).with("sms");
}
}
EmailService
@Service
@RabbitListener(queues = "email.direct.queue")
public class EmailService {
@RabbitHandler
public void email(String msg){
System.out.println("email recive-------------->"+msg);
}
}
SmsService
@Service
@RabbitListener(queues = "sms.direct.queue")
public class SmsService {
@RabbitHandler
public void sms(String msg){
System.out.println("sms recive------------->"+msg);
}
}
5 、测试
启动消费者工程,生成交换机和消息队列
启动producer工程中的测试类contextLoads(),发送消息
consumer消费到消息