RabbitMQ学习系列 二 “Hello World”
前面写了RabbitMQ的安装,这一篇记录一下 “Hello World” 的实现 。
[TOC]
介绍
使用最简单的方式发布一个消息并接收
这里声明了一个hello队列,没有使用路由。
编写生产者
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class Send { private final static String QUEUE_NAME="hello";
public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("localhost"); Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME,false,false,false,null); String message = "HJW,Hello World!"; channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
channel.close(); connection.close(); } }
|
编写消费者
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public class Recv { private final static String QUEUE_NAME ="hello";
public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("localhost"); connectionFactory.setUsername("guest"); connectionFactory.setPassword("guest"); connectionFactory.setPort(5672); Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME,false,false,false,null); 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(" Message is received: " + message ); } }; channel.basicConsume(QUEUE_NAME, true, consumer); } }
|
方法介绍
1、队列声明
queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
queue:队列名称
durable:是否持久化
exclusive:是否为排它队列。即只有自己可见,对首次连接可见,连接断开自动删除
autoDelete:是否自动删除,在没有消费者的时候
arguments:其它参数
2、发布消息
basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body)
exchange:路由名
routingKey:发布到哪个队列
props: 其它参数
body: 消息体
3、订阅消息并消费
basicConsume(String queue, boolean autoAck, Consumer callback)
queue:消息队列名
autoAck: 是否自动确认。消息被消息后需要向rabbitmq返回一个确认,rabbitmq才会把消息删除,也可以手动确认
callback: 消费者