rabbitmq direct、fanout、topic 三种Exchange java 代码比较

Producer端

1、channel的创建

  无论是才用什么样的Exchange,创建channel代码都是相同的,如下  

1 ConnectionFactory factory = new ConnectionFactory();
2 factory.setHost("localhost");
3 Connection connection = factory.newConnection();
4 Channel channel = connection.createChannel();

 

2、Exchange的创建

 2.1 direct

  direct使用默认的Exchange,不需要声明,单需要指定消息发送到那个队列

channel.queueDeclare(QUEUE_NAME, false, false, false, null);

 2.2 fanout

channel.exchangeDeclare(EXCHANGE_NAME, "fanout")

 

 2.3 topic如下

channel.exchangeDeclare(EXCHANGE_NAME, "topic");

3、消息的发送

  3.1 direct

channel.basicPublish("", QUEUE_NAME, null, message.getBytes());

  3.2 fanout 

 

channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());

  3.3 topic

 

channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes());

 

cusumer端

1、创建channel 

ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

2、消息前的准备

   2.1  direct直接绑定队列进行消息的消费        

chanel.queueDeclare(QUEUE_NAME, false, false, false, null);

   2.2 fanout,需要先指定exchange类型为fanout 

channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, EXCHANGE_NAME, "");

  2.3 topic       

channel.exchangeDeclare(EXCHANGE_NAME, "topic");
String queueName = channel.queueDeclare().getQueue();
 for(String bindingKey : argv){
      channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);
 }

3、具体消费消息的代码是一样的

     

复制代码
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(QUEUE_NAME, true, consumer);
while (true) {
    QueueingConsumer.Delivery delivery = consumer.nextDelivery();
    Envelope elp = delivery.getEnvelope();
    String message = new String(delivery.getBody());
    System.out.println(" [x] Received '" + message + "'");
    channel.basicAck(elp.getDeliveryTag(), false);
    //channel.basicNack();
​}
复制代码
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值