RabbitMQ消费和生产代码示例
Consumer
import com.rabbitmq.client.*;
public class Consumer {
public static String QUEUE_NAME="hello";
public static void main(String[] args) throws Exception{
// 创建工厂
ConnectionFactory factory =new ConnectionFactory();
factory.setHost("192.168.3.128");
factory.setUsername("admin");
factory.setPassword("123456");
// 创建链接
Connection connection =factory.newConnection();
// 获取信道
Channel channel = connection.createChannel();
// 消费者消费消息
/**
* 1.消费那个队列
* 2.消费成功之后是否要自动应答 true自动 false手动应答\
* 3.未成功消费的回调
* 4.取消消费的回调
*/
// (声明 接收消息)接受消息回调函数
DeliverCallback deliverCallback = (con,mes)->{
// String message=new Strin
// 打印消息
System.out.println(new String(mes.getBody()));
System.out.println("你好世界");
};
// 取消消息回调函数
CancelCallback cancelCallback = con ->{
System.out.println("消费消息被中断");
};
channel.basicConsume(QUEUE_NAME,true,deliverCallback,cancelCallback);
}
}
Producer
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Producer {
// 队列,名称
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws Exception {
//创建一个连接工厂
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.3.128");
factory.setUsername("admin");
factory.setPassword("123456");
// 创建链接
Connection connection =factory.newConnection();
// 获取信道
Channel channel = connection.createChannel();
// 创建队列
channel.queueDeclare(QUEUE_NAME, true, false, true, null);
// 发消息
String message="hell word";
channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
System.out.println("succeed!!!");
}
}
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">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>com.rabbitmq</artifactId>
<version>1.0-SNAPSHOT</version>
<!--指定 jdk 编译版本-->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- <dependency>-->
<!-- <groupId>org.slf4j</groupId>-->
<!-- <artifactId>slf4j-nop</artifactId>-->
<!-- </dependency>-->
<!--rabbitmq 依赖客户端-->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.8.0</version>
</dependency>
<!--操作文件流的一个依赖-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
</project>
本文提供Java环境下RabbitMQ的消费者(Consumer)和生产者(Producer)的代码示例,帮助理解如何在实际应用中使用RabbitMQ进行消息传递。
2520

被折叠的 条评论
为什么被折叠?



