rabbitmq java 应用实例

增长maven配置文件
java

<dependency>
		<groupId>com.rabbitmq</groupId>
		<artifactId>amqp-client</artifactId>
		<version>3.6.5</version>
	</dependency>
复制代码

生产者
package com.jeff.boot.controller.rabbitmq; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.io.IOException; import java.util.concurrent.TimeoutException;服务器

public class Producer { public final static String QUEUE_NAME="rabbitMQtest";maven

public static void main(String[] args) throws IOException, TimeoutException {
    //建立链接工厂
    ConnectionFactory factory = new ConnectionFactory();
    //设置RabbitMQ相关信息
    factory.setHost("");
    factory.setUsername("");
    factory.setPassword("");
    factory.setPort(5672);
    //建立一个新的链接
    Connection connection = factory.newConnection();
    //建立一个通道
    Channel channel = connection.createChannel();
    //  声明一个队列
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    String message = "Hello RabbitMQ";
    int i = 0;
    //发送消息到队列中
    while (i < 100 ) {
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
        System.out.println("Producer Send +'" + message + "'");
        //关闭通道和链接
        i++;
    }
    channel.close();
    connection.close();
}
复制代码

}ide

消费者
package com.jeff.boot.controller.rabbitmq;函数

import com.rabbitmq.client.*; import java.io.IOException; import java.util.concurrent.TimeoutException;spa

public class Customer { private final static String QUEUE_NAME = "rabbitMQtest";code

public static void main(String[] args) throws IOException, TimeoutException {
    // 建立链接工厂
    ConnectionFactory factory = new ConnectionFactory();
    //设置RabbitMQ地址
    factory.setHost("192.168.226.53");
    //建立一个新的链接
    Connection connection = factory.newConnection();
    //建立一个通道
    Channel channel = connection.createChannel();
    //声明要关注的队列

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    System.out.println("Customer Waiting Received messages");
    //DefaultConsumer类实现了Consumer接口,经过传入一个频道,
    // 告诉服务器咱们须要那个频道的消息,若是频道中有消息,就会执行回调函数handleDelivery
    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("Customer Received '" + message + "'");
        }
    };
    //自动回复队列应答 -- RabbitMQ中的消息确认机制
    channel.basicConsume(QUEUE_NAME, true, consumer);
}
复制代码

}接口

相关文章
相关标签/搜索