文章参考:Rabbit实战指南
生产者客户端代码
public class RabbitProducer{
private static final String EXCHANGE_NAME = "exchange_demo";
private static final String ROUTING_KEY = "routingkey_demo";
private static final String QUEUE_NAME = "queue_demo";
private static final String IP_ADDRESS = "10.20.12.211";
private static final int PORT = 5672; //RabbitMQ服务端默认端口号
public static void main(String[] args) throws IOException,TimeoutException,InterruptedException{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(IP_ADDRESS);
factory.setUsername("guest");
factory.setPassword("guest");
//创建连接
Connection connection = factory.newConnection();
//创建信道
Channel channel = connection.createChannel();
//创建一个type='direct'、持久化的、非自动删除的队列
channel.exchangeDeclare(EXCHANGE_NAME,"direct",true,false,null);
//创建一个持久化、非排他的、非自动删除的队列
channel.queueDeclare(QUEUE_NAME,true,false,false,null);
//将交换器与队列通过路由键绑定
channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,ROUTING_KEY);
//发送一条持久化的信息:hello world!
String message = "hello world!";
channel.basicPublish(EXCHANGE_NAME,ROUTING_KEY,
MessageProperties.PERSISTENT_TEXT_PLAIN,
message.getBytes());
//关闭资源
channel.close();
connection.close();
}
}
消费者客户端代码
public class RabbitConsumer{
private static final String QUEUE_NAME = "queue_demo";
private static final String IP_ADDRESS = "10.20.12.211";
private static final int PORT = 5672;
public static void main(String[] args) throws IOException, TimeoutException,
InterruptedException{
Address[] address = new Address[]{
new Address(IP_ADDRESS,PORT)
};
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("zhou_jiangcheng");
factory.setPassword("zhou19970407");
//这里的连接方式和生产者的demo略有不同
//创建连接
Connection connection = factory.newConnection(address);
//创建信道
final Channel channel = connection.createChannel();
//设置客户端最多接受违背ack的消息的个数
channel.basicQos(64);
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag,Envelope envelope,
AMQP.BasicProperties properties,
byte[] body) throws IOException{
System.out.println("recv message:" + new String(body));
try{
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e){
e.printStackTrace();
}
channel.basicAck(envelope.getDeliveryTag(),false);
}
};
channel.basicConsume(QUEUE_NAME,consumer);
//等待回调函数执行完毕之后,关闭资源
TimeUnit.SECONDS.sleep(5);
channel.close();
connection.close();
}
}
channel.basicConsume(QUEUE_NAME,true,consumer);
若autoAck为true,可以不用使用channel.basicAck(envelope.getDeliveryTag(),false);
进入到handleDelivery()时,全部消费。
channel.basicConsume(QUEUE_NAME,consumer);
若autoAck为false,必须使用channel.basicAck(envelope.getDeliveryTag(),false);
进入到handleDelivery()时,消息全部进入到unacked状态,最后才全部执行完。