青蛙小白

使用RabbitMQ Java Client

Publishing Messages 连接到Broker 获取Channel 声明一个Exchange 创建一个Message 发布这个Message 关闭Channel 关闭Connection ConnectionFactory connectionFactory = new ConnectionFactory(); // AMQP URI amqp://userName:password@hostName:portNumber/virtualHost" connectionFactory.setUri("amqp://test:[email protected]:5672/demo"); Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare("first-exchange", "direct", true); byte[] msgBody = "Hello, World!".getBytes("UTF-8"); channel.basicPublish("first-exchange", "helloRoutingKey", null, msgBody); channel.close(); connection.close(); Receiving Messages by Subscription public static void main(String[] args) throws Exception { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri("amqp://test:[email protected]:5672/demo"); Connection connection = connectionFactory.newConnection(); final Channel channel = connection.createChannel(); channel.exchangeDeclare("first-exchange", "direct", true); channel.queueDeclare("hello-queue", true, false, false, null); channel.queueBind("hello-queue", "first-exchange", "helloRoutingKey"); channel.basicConsume("hello-queue", new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException { String msg = new String(body, "UTF-8"); System.out.println(msg); channel.basicAck(envelope.getDeliveryTag(), false); } }); Scanner scanner = new Scanner(System.in); scanner.nextLine(); scanner.close(); channel.close(); connection.close(); }

AMQP协议简介

简介 AMQP即Advanced Message Queuing Protocol,高级消息队列协议,是面向消息中间件设计的应用层协议的一个开放标准。 它的主要特点是面向消息、队列、路由(包括点对点和发布/订阅)]、可靠性和安全。 AMQP允许来自不同供应商的消息生产者和消费者实现真正的互操作扩展,就如同SMTP、HTTP、FTP等协议采用的方式一样。而此前对于消息中间件的标准化努力则集中在API层面上(比如JMS),且没有提供互操作性的途径。不同于JMS的仅仅定义API,AMQP是一个线路级的协议——它描述了通过网络传输的字节流的数据格式。因此,遵从这个协议的任何语言编写的工具均可以操作AMQP消息。