ps:X表示交换器,在RabbitMQ中,交换器主要有四种类型:direct、fanout、topic、headers
生产者发送消息类:
package com..pubsub; import com..utils.RabbitConstant; import com..utils.RabbitUtils; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import java.io.IOException; import java.util.Scanner; import java.util.concurrent.TimeoutException; public class WeatherBureau { public static void main(String[] args) throws IOException, TimeoutException { Connection connection = RabbitUtils.getConnection(); //input为 接收控制台输入的数据 String input = new Scanner(System.in).next(); Channel channel = connection.createChannel(); channel.basicPublish(RabbitConstant.EXCHANGE_WEATHER,"" , null , input.getBytes()); channel.close(); connection.close(); } }
后台打印信息:
消费者1(百度):
package com..pubsub; import com..utils.RabbitConstant; import com..utils.RabbitUtils; import com.rabbitmq.client.*; import java.io.IOException; public class Baidu { public static void main(String[] args) throws IOException { Connection connection = RabbitUtils.getConnection(); final Channel channel = connection.createChannel(); channel.queueDeclare(RabbitConstant.QUEUE_BAIDU, false, false, false, null); //queueBind用于将队列与交换机绑定 //参数1:队列名 参数2:交互机名 参数三:路由key(暂时用不到) channel.queueBind(RabbitConstant.QUEUE_BAIDU, RabbitConstant.EXCHANGE_WEATHER, ""); channel.basicQos(1); channel.basicConsume(RabbitConstant.QUEUE_BAIDU , false , new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("百度收到信息:" + new String(body)); channel.basicAck(envelope.getDeliveryTag() , false); } }); } }
后台打印信息:
消费者2(新浪)
package com.wondersgroup.pubsub; import com.wondersgroup.utils.RabbitConstant; import com.wondersgroup.utils.RabbitUtils; import com.rabbitmq.client.*; import java.io.IOException; public class Sina { public static void main(String[] args) throws IOException { Connection connection = RabbitUtils.getConnection(); final Channel channel = connection.createChannel(); channel.queueDeclare(RabbitConstant.QUEUE_SINA, false, false, false, null); //queueBind用于将队列与交换机绑定 //参数1:队列名 参数2:交互机名 参数三:路由key(暂时用不到) channel.queueBind(RabbitConstant.QUEUE_SINA, RabbitConstant.EXCHANGE_WEATHER, ""); channel.basicQos(1); channel.basicConsume(RabbitConstant.QUEUE_SINA , false , new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("新浪收到信息:" + new String(body)); channel.basicAck(envelope.getDeliveryTag() , false); } }); } }
后台打印信息: