java客户端声明RabbitMq交换机和队列的两种方法

1.方法一:使用Bean

未声明前RabbitMq客户端情况

相关java代码:

1.1声明队列、交换机以及绑定

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MqConfig {
    // 交换机名称
    public static final String EXCHANGE_NAME = "hello.direct";
    // 队列名称
    public static final String QUEUE_NAME = "hello.queue";
    // 传递key
    public static final String KEY = "hello";

    @Bean
    public DirectExchange directExchange(){
        // return new DirectExchange(EXCHANGE_NAME); // 直接new一个交换机对象
        return ExchangeBuilder.directExchange(EXCHANGE_NAME).build(); //通过ExchangeBuilder创建
    }
    @Bean
    public Queue helloQueue(){
        // return new Queue(QUEUE_NAME);
        return QueueBuilder.durable(QUEUE_NAME).build();
    }

    @Bean
    public Binding directBinding(){
        return BindingBuilder.bind(helloQueue()).to(directExchange()).with(KEY);
    }
}

1.2 监听代码

import com.example.rabbitmq.config.MqConfig;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class MqListener {
    @RabbitListener(queues = MqConfig.QUEUE_NAME)
    public void listenHello(Long id){
        System.out.println(id);
    }
}

声明后RabbitMq客户端情况

2:RabbitListener注解方法

直接写监听代码

import com.example.rabbitmq.config.MqConfig;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class MqListener {
    @RabbitListener(queues = MqConfig.QUEUE_NAME)
    public void listenHello(Long id){
        System.out.println(id);
    }

    /**
     * @QueueBinding绑定
     * value 队列
     * exchange 交换机
     * key 传递key
     * */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "world.queue"),
            exchange = @Exchange(name = "world.direct", type = ExchangeTypes.DIRECT),
            key = {"world"}
    ))
    public void listenWorld(Long id){
        System.out.println(id);
    }
}

RabbitMq客户端情况

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

该睡觉了839

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值