前言:首先你要启动rabbitMQ
第一步,创建maven项目,设置依赖
<!--rabbit依赖-->
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.3.5</version>
</dependency>
<!--web依赖可加-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.4.3</version>
</dependency>
第二部,代码部分
生产者代码(发送)
public class Send {
private final static String QUEUE_NAME = "Somnus";
public static void main(String[] args) throws IOException, TimeoutException {
// 创建连接 工厂
ConnectionFactory factory = new ConnectionFactory();
// 设置MabbitMQ, 主机ip或者主机名
// factory.setUsername("guest");
// factory.setPassword("guest");
factory.setHost("127.0.0.1");
// 创建一个连接
Connection connection = factory.newConnection();
// 创建一个通道
Channel channel = connection.createChannel();
// 指定一个队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
// 发送消息
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] 发送消息是:'" + message + "'");
// 关闭连接
channel.close();
connection.close();
}
}
消费者代码(接收)
public class Receive {
private final static String QUEUE_NAME = "Somnus";
public static void main(String[] args) throws IOException, TimeoutException {
// 创建连接
ConnectionFactory factory = new ConnectionFactory();
// 设置MabbitMQ, 主机ip或者主机名
factory.setHost("127.0.0.1");
// 创建一个连接
Connection connection = factory.newConnection();
// 创建一个通道
Channel channel = connection.createChannel();
// 指定一个队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] 等待消息进入. 请按 CTRL+C 结束");
// 创建队列消费者
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
byte[] body) throws IOException {
String message = new String(body, "UTF-8");
System.out.println(" [x] 接收消息是: '" + message + "'");
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}
结束语:不加web依赖会报这个异常,但是不影响我们简单得测试