RabbitMQ路由模式(Direct)实现和原理步骤讲解,方式4

简单工作队类的实现配置步骤(5步)

  1. 引入AMQP的依赖
  2. 创建配置文件,链接消息队列(port name MQ账号密码)
  3. 创建配置类,声明队列
  4. 使用消息生产者发送消息
  5. 使用消息消费者接受消息

1 引入AMQP的依赖

			<dependency>
	            <groupId>org.springframework.boot</groupId>
	            <artifactId>spring-boot-starter-amqp</artifactId>
	        </dependency>
  1. 创建配置文件,链接消息队列(port name MQ账号密码)
server:
  port: 9004
spring:
  application:
    name: demo04
  rabbitmq:
    host: 120.55.58.250
    port: 5672
    password: guest
    username: guest

  1. 创建配置类,声明队列
@Configuration
public class DirectQueueConfig {
    public static String queueName01="direct.queue01";
    public static String queueName02="direct.queue02";
    public static String exchangeName="direct.exchange";
    @Bean
    public Queue directQueue01(){
        return new Queue(queueName01);
    }
    @Bean
    public Queue directQueue02(){
        return new Queue(queueName02);
    }


    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange(exchangeName);
    }
    @Bean
    //绑定交换机和队列
    public Binding bindingQueue01(Queue directQueue01, DirectExchange directExchange){
        return BindingBuilder.bind(directQueue01).to(directExchange).with("routingkey.A");
    }

    @Bean
    //绑定交换机和队列
    public Binding bindingQueue02(Queue directQueue02,DirectExchange directExchange){
        return BindingBuilder.bind(directQueue02).to(directExchange).with("routingkey.B");
    }
}
  1. 使用消息生产者发送消息
@RestController
public class TestController {
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @RequestMapping("/sendMessage01")
    public void sendMessage01(){
        for (int i=1;i<=5;i++){
            rabbitTemplate.convertAndSend("direct.exchange","routingkey.A","路由模式routingA"+i);
        }
    }

    @RequestMapping("/sendMessage02")
    public void sendMessage02(){
        for (int i=1;i<=5;i++){
            rabbitTemplate.convertAndSend("direct.exchange","routingkey.B","路由模式routingB"+i);
        }
    }
}
  1. 使用消息消费者接受消息
@Component
public class ReceiveListener {
    @RabbitListener(queues="direct.queue01")
    public void ReceiveMessage01(String message){
        System.out.println("ReceiveMessage01"+message);
    }

    @RabbitListener(queues="direct.queue02")
    public void ReceiveMessage02(String message){
        System.out.println("ReceiveMessage02"+message);
    }
}

测试地址

http://localhost:9004/sendMessage01
 http://localhost:9004/sendMessage02

结果展示
http://localhost:9004/sendMessage01
在这里插入图片描述

 http://localhost:9004/sendMessage02
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/73678c1564a54d5b944f07190c55c357.png#pic_center)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值