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);
}
複製代碼

}接口

相關文章
相關標籤/搜索