Routing key由生产者指定。Binding key由消费者指定。二者联合决定一条消息的来去。
maven依赖
<dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>3.6.1</version> </dependency>
连接范例:
ConnectionFactory factory = new ConnectionFactory(); factory.setUsername(userName); factory.setPassword(password); factory.setVirtualHost(virtualHost); factory.setHost(hostName); factory.setPort(portNumber); Connection conn = factory.newConnection();
简便方式:
ConnectionFactory factory = new ConnectionFactory(); factory.setUri("amqp://userName:password@hostName:portNumber/virtualHost"); Connection conn = factory.newConnection();
最后这个channel就可以用来收和发消息了。
Channel channel = conn.createChannel();
提醒:
请在程序结尾处关闭链接,否则比较耗费资源:
channel.close(); conn.close();
使用Exchanges and Queues
channel.exchangeDeclare(exchangeName, "direct", true); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, exchangeName, routingKey);
byte[] messageBodyBytes = "Hello, world!".getBytes(); channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);
boolean autoAck = false; channel.basicConsume(queueName, autoAck, "myConsumerTag", new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String routingKey = envelope.getRoutingKey(); String contentType = properties.getContentType(); long deliveryTag = envelope.getDeliveryTag(); // (process the message components here ...) channel.basicAck(deliveryTag, false); } });
参考官方文档:
http://www.rabbitmq.com/api-guide.html
官方api
http://www.rabbitmq.com/releases/rabbitmq-java-client/v3.6.1/rabbitmq-java-client-javadoc-3.6.1/
简单易行,这样的工具,使我们需要的,也是我们想要的,看着国外N多好用的中间件,一个接一个出现,国内虽然这些年也改变了不少,但是我们和国外优秀的团队和开发理念上还是有差距的,随着阅读外国api的次数增多,量的累计,我相信,我们也会慢慢优秀起来,追赶超越!