1.依赖
<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>
2.生产者
public class Producer {
public static final String QUEUE_NAME = "hello";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
//连接RabbitMQ队列
factory.setHost("127.0.0.1");
//设置用户名 密码
factory.setUsername("guest");
factory.setPassword("guest");
//创建连接
Connection connection = factory.newConnection();
//获取信道
Channel channel = connection.createChannel();
/**
* 生成队列
* 1.队列名称
* 2.队列里面的消息是否持久化(磁盘) 默认在内存
* 3.该队列是否只供一个消费者进行消费,是否进行消息共享
* 4.是否自动删除 最后一个消费者断开连接以后 该队列是否删除
* 5.其他参数
*/
channel.queueDeclare(QUEUE_NAME, false, false, false,null);
String message = "HW";
/**
* 发送一个消费
* 1.发送到那个交换机
* 2.路由的key 是队列的名称
* 3.其他参数消息
* 4.发送消息的消息体
*/
channel.basicPublish("",QUEUE_NAME,null,message.getBytes(StandardCharsets.UTF_8));
System.out.println("Success");
}
}
3.消费者
public class Consumer {
public static final String QUEUE_NAME = "hello";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
//连接RabbitMQ队列
factory.setHost("127.0.0.1");
//设置用户名 密码
factory.setUsername("guest");
factory.setPassword("guest");
//创建连接
Connection connection = factory.newConnection();
//获取信道
Channel channel = connection.createChannel();
/**
* 接受消息
* 1.消费那个队列
* 2.消费成功之后是否要自动应答
* 3.消费者未成功消费的回调
* 4.取消消费的回调
*/
//声明
DeliverCallback deliverCallback = (counsumerTag , message) -> {
System.out.println(new String(message.getBody()));
};
CancelCallback cancelCallback = counsumerTag -> {
System.out.println("消息被中断");
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback,cancelCallback);
}
}
标签:String,队列,factory,HelloWorld,QUEUE,public,NAME
From: https://www.cnblogs.com/lwx11111/p/17411151.html