rabbitmq fanout java_java操作rabbitmq的订阅模式fanout

就是发送一个消息所有的订阅的消费都可以接收

145f36f205ef

1消费者把消息发布在交换机

2消费者去交换机订阅消息

3一旦交换机有消息就会给消费者进行消费

发送者:

import com.rabbitmq.client.Channel;

import com.rabbitmq.client.Connection;

import java.io.IOException;

public class SendDyue {

private  static  final  StringEXCHANGE_NAME="fanout";

public static void main(String[] args)throws IOException {

///的创建连接

Connection connection  =RabbitMqUtils.getConnection();

//通道对象

Channel  channel  =connection.createChannel();

//声明交换机

channel.exchangeDeclare(EXCHANGE_NAME,"fanout");

//发布消息

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

//自愿关闭

channel.close();

connection.close();

}

}

接受者01:

import com.rabbitmq.client.*;

import java.io.IOException;

public class RevFanOut01 {

private  static  final  StringEXCHANGE_NAME="fanout";

private  static  final  StringQUEUE_NAME="fanoutres01";

public static void main(String[] args)throws IOException {

Connection connection  =RabbitMqUtils.getConnection();

Channel channel  =  connection.createChannel();

//声明交换机

channel.exchangeDeclare(EXCHANGE_NAME,"fanout");

//声明队列

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

//绑定队列到交换机中

channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"");

//定义消费者接收消息

DefaultConsumer  defaultConsumer  =new DefaultConsumer(channel){

@Override

public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,byte[] body)throws IOException {

super.handleDelivery(consumerTag, envelope, properties, body);

String  s =new String(body);

System.out.println("消费者1"+s);

//手动应答服务端

channel.basicAck(envelope.getDeliveryTag(),false);

}

};

//接收消息

channel.basicConsume(QUEUE_NAME,false,defaultConsumer);

}

}

接受者2:

import com.rabbitmq.client.*;

import java.io.IOException;

public class RevFanOut02 {

private  static  final  StringEXCHANGE_NAME="fanout";

private  static  final  StringQUEUE_NAME="fanoutres02";

public static void main(String[] args)throws IOException {

Connection connection  =RabbitMqUtils.getConnection();

Channel channel  =  connection.createChannel();

//声明交换机

channel.exchangeDeclare(EXCHANGE_NAME,"fanout");

//声明队列

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

//绑定队列到交换机中

channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"");

//定义消费者接收消息

DefaultConsumer defaultConsumer  =new DefaultConsumer(channel){

@Override

public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,byte[] body)throws IOException {

super.handleDelivery(consumerTag, envelope, properties, body);

String  s =new String(body);

System.out.println("消费者2"+s);

//手动应答服务端

channel.basicAck(envelope.getDeliveryTag(),false);

}

};

//接收消息

channel.basicConsume(QUEUE_NAME,false,defaultConsumer);

}

}

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页