首先pom依赖:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>springcloudparent</artifactId> <groupId>com.cxy</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>rabbitMqConsumer</artifactId> <dependencies> <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.4.3</version> </dependency> </dependencies> </project>
生产者代码:
package com.cxy.producer; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.io.IOException; import java.util.concurrent.TimeoutException; /*** * @ClassName: Producer1 * @Description: * @Auther: cxy * @Date: 2019/3/24:11:38 * @version : V1.0 */ public class Producer1 { private static final String Queue="helloworld"; public static void main(String[] args) { ConnectionFactory connectionFactory= new ConnectionFactory(); //设置连接地址 connectionFactory.setHost("192.168.230.134"); //设置端口 connectionFactory.setPort(5672); //设置密码用户名 connectionFactory.setUsername("guest"); connectionFactory.setPassword("guest"); //设置虚拟机,每个虚拟机相当于一个小的mq connectionFactory.setVirtualHost("/"); Connection connection =null; try { //建立连接 connection = connectionFactory.newConnection(); //建立通道,生产着和消费者都是在通道中完成 Channel channel = connection.createChannel(); /* queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments) 参数1,声明队列 参数2 是否持久化 参数3 是否排他,是否独战连接,队列只允许该链接中访问,如果连接关闭,队列也就删除了 参数4:是否自动删除,如果将此参数设置true,那么就变成零时队列 参数5 :扩展参数,例如存活时间 */ channel.queueDeclare(Queue,true,false,false,null); //所有的队列需要制定默认的交换机 /* basicPublish(String exchange, String routingKey, boolean mandatory, boolean immediate, BasicProperties props, byte[] body) throws IOException; 参数1: 交换机,如果使用默认交换机,那么就为空,不可以设置为null 参数二:路由key.交换机根据key来将消息发送到制定搞得队列,如果私用默认交互机,就应该设置为队列名称 */ String message="hello maxchen"; channel.basicPublish(null,Queue,null,message.getBytes()); System.out.println("send xiaoxi"); } catch (IOException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } } }
运行为报错L:
Exception in thread "main" java.lang.IllegalStateException: Invalid configuration: 'exchange' must be non-null. at com.rabbitmq.client.impl.AMQImpl$Basic$Publish.<init>(AMQImpl.java:3195) at com.rabbitmq.client.AMQP$Basic$Publish$Builder.build(AMQP.java:1219) at com.rabbitmq.client.impl.ChannelN.basicPublish(ChannelN.java:702) at com.rabbitmq.client.impl.ChannelN.basicPublish(ChannelN.java:679) at com.rabbitmq.client.impl.ChannelN.basicPublish(ChannelN.java:669) at com.rabbitmq.client.impl.recovery.AutorecoveringChannel.basicPublish(AutorecoveringChannel.java:192) at com.cxy.producer.Producer1.main(Producer1.java:56)
处理方法:
再看管控台: