版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hxg117/article/details/82660277
主要步骤:
- 创建Exchange
- 创建Queue
- 使用RoutingKey绑定Exchange到Queue
- 向Exchange发送消息,需要设置消息的RoutingKey
- Exchange收到消息后根据RoutingKey绑定转发消息到Queue
- 从Queue读取消息
Maven依赖:
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
使用amqp-client,ConnectionFactory->Connection->Channel。使用Channel声明Exchange,Queue,并通过RoutingKey绑定Queue到Exchange。使用channel发送和接收消息。
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");
factory.setPort(5672);
Connection cn = factory.newConnection();
Channel channel = cn.createChannel();
String exchange = "TestExchange";
String routingKey = "TestRoutingKey";
String queue = channel.queueDeclare().getQueue();
channel.exchangeDeclare(exchange, "direct");
channel.queueBind(queue, exchange, routingKey);
channel.basicConsume(queue, new DefaultConsumer(channel){
@Override
public void handleDelivery(String tag, Envelope envelope, BasicProperties props, byte[] body)
throws IOException {
System.out.println("Received: " + new String(body));
}
});
System.out.println("Sending.");
channel.basicPublish(exchange, routingKey, null, "Hello".getBytes());
Thread.sleep(100);
channel.exchangeDelete(exchange);
cn.close();
}
如果使用Spring,RabbitTemplate,大致流程如下:
public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = new CachingConnectionFactory("127.0.0.1", 5672);
String exchange = "TestExchange2";
String routingKey = "TestRoutingKey2";
String queue = "TestQueue2";
RabbitAdmin admin = new RabbitAdmin(connectionFactory);
admin.declareQueue(new Queue(queue));
admin.declareExchange(new DirectExchange(exchange));
admin.declareBinding(BindingBuilder.bind(new Queue(queue)).to(new DirectExchange(exchange)).with(routingKey));
RabbitTemplate template = new RabbitTemplate(connectionFactory);
template.setExchange(exchange);
template.convertAndSend(routingKey, "Hello");
System.out.println("Received: " + template.receiveAndConvert(queue));
}