RabbitMQ - Hello World!

Posted jmbkeyes

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RabbitMQ - Hello World!相关的知识,希望对你有一定的参考价值。

添加 gradle依赖complie("com.rabbitmq:amqp-client:5.0.0")

Producer:

    private static void helloWorld() {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel();) {

            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            String message = "Hello, World!";

            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            System.out.println("[x] send ‘" + message + "‘");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

Consumer:

    private static void helloWorld() {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel();) {
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);

            System.out.println("[*] Waiting for message");

            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerFlag, Envelope envelope, AMQP.BasicProperties properties,
                        byte[] body) throws UnsupportedEncodingException {
                    String message = new String(body, "UTF-8");
                    System.out.println("[x] Receive message:‘" + message + "‘");
                }
            };
            channel.basicConsume(QUEUE_NAME, consumer);
            System.out.println("aaaa");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

 

以上是关于RabbitMQ - Hello World!的主要内容,如果未能解决你的问题,请参考以下文章

消息队列RabbitMQ核心:简单(Hello World)模式队列(Work Queues)模式发布确认模式

RabbitMQ - Hello World!

RabbitMQ消息队列:”Hello, World“

RabbitMQ消息队列:”Hello, World“

RabbitMQ文档翻译——Hello World!(下)

RabbitMQ ——“Hello World”